I have this code that creates a Jframe where I add a JLabel with a picture and a JpasswordField. I want the JpasswordField to be on top of the image but only depending on where I do the f.add I get one of them showed or not... I want the JpasswordField to be on top of the picture to allow the user to introduce a password but with the picture as background.
Here is the code:
package java;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
public class Java implements Runnable {
public static void main(String[] args) {
EventQueue.invokeLater(new Java());
}
#Override
public void run() {
JFrame f = new JFrame();
/*Keep on front*/
f.toFront();
f.repaint();
f.setAlwaysOnTop(true);
f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
f.setBounds(0,0,screenSize.width-5, screenSize.height-100);
double width = screenSize.getWidth();
double height = screenSize.getHeight();
System.out.println(width+" "+height);
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("C:\\image.jpg"));
} catch (IOException e1) {
e1.printStackTrace();
}
Image dimg = myPicture.getScaledInstance((int)width, (int)height,Image.SCALE_SMOOTH);
JLabel picLabel = new JLabel(new ImageIcon(dimg));
JPasswordField myTextfield = new JPasswordField("Password");
myTextfield.setEchoChar('*'); // U+26AB
picLabel.setPreferredSize(screenSize);
picLabel.setVerticalAlignment(JLabel.BOTTOM);
/*Depending of who I add first the image or the JPasswordField is showed*/
f.add(myTextfield);
f.add(picLabel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
First off, your code should be geared towards creating JPanels, and you should control the layout manager of this JPanel directly. Then you can place and display your JPanel in a JDialog not a JFrame, since much of your code appears to be trying to emulate a dialog's actions (such as keeping it on top and such).
That being sad, one of your big problems is that you're ignoring the layout manager that the JFrame's contentPane is using, the BorderLayout. By adding components to it in a default fashion, you will cover up anything that was added to the same position previously. Instead I suggest:
Create a JPanel
Draw your image as a background image in the JPanel's paintComponent methd.
Add your JLabel to your JPanel.
Display the JPanel in a JDialog not a JFrame.
For example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class DialogExample extends JPanel {
private static final int COLUMN_COUNT = 10;
private static final int I_GAP = 3;
public static final String BKG_IMG_PATH = "http://upload.wikimedia.org/wikipedia/commons/"
+ "thumb/9/92/Camels_in_Jordan_valley_%284568207363%29.jpg/800px-Camels_in_Jordan_valley_"
+ "%284568207363%29.jpg";
private BufferedImage backgrndImage;
private JTextField userNameField = new JTextField();
private JPasswordField passwordField = new JPasswordField();
private JPanel mainPanel = new JPanel(new GridBagLayout());
private JButton okButton = new JButton("OK");
private JButton cancelButton = new JButton("Cancel");
public DialogExample(BufferedImage backgrndImage) {
this.backgrndImage = backgrndImage;
userNameField.setColumns(COLUMN_COUNT);
passwordField.setColumns(COLUMN_COUNT);
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
btnPanel.setOpaque(false);
btnPanel.add(okButton);
btnPanel.add(cancelButton);
GridBagConstraints gbc = getGbc(0, 0, GridBagConstraints.BOTH);
mainPanel.add(createLabel("User Name", Color.white), gbc);
gbc = getGbc(1, 0, GridBagConstraints.HORIZONTAL);
mainPanel.add(userNameField, gbc);
gbc = getGbc(0, 1, GridBagConstraints.BOTH);
mainPanel.add(createLabel("Password:", Color.white), gbc);
gbc = getGbc(1, 1, GridBagConstraints.HORIZONTAL);
mainPanel.add(passwordField, gbc);
gbc = getGbc(0, 2, GridBagConstraints.BOTH, 2, 1);
mainPanel.add(btnPanel, gbc);
mainPanel.setOpaque(false);
add(mainPanel);
}
private JLabel createLabel(String text, Color color) {
JLabel label = new JLabel(text);
label.setForeground(color);
return label;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgrndImage != null) {
g.drawImage(backgrndImage, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || backgrndImage == null) {
return super.getPreferredSize();
}
int imgW = backgrndImage.getWidth();
int imgH = backgrndImage.getHeight();
return new Dimension(imgW, imgH);
}
public static GridBagConstraints getGbc(int x, int y, int fill) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
gbc.fill = fill;
return gbc;
}
public static GridBagConstraints getGbc(int x, int y, int fill, int width,
int height) {
GridBagConstraints gbc = getGbc(x, y, fill);
gbc.gridwidth = width;
gbc.gridheight = height;
return gbc;
}
private static void createAndShowGui() throws IOException {
final JFrame frame = new JFrame("Frame");
final JDialog dialog = new JDialog(frame, "User Sign-In", ModalityType.APPLICATION_MODAL);
URL imgUrl = new URL(BKG_IMG_PATH);
BufferedImage img = ImageIO.read(imgUrl);
final DialogExample dlgExample = new DialogExample(img);
dialog.add(dlgExample);
dialog.pack();
JPanel mainPanel = new JPanel();
mainPanel.add(new JButton(new AbstractAction("Please Press Me!") {
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(true);
}
}));
mainPanel.setPreferredSize(new Dimension(800, 650));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Just to give one example (amongst many other possibilities), here is a small snippet that shows how to handle this.
Btw, when you call f.pack(); f.setLocationRelativeTo(null);, then this call is useless: f.setBounds(0,0,screenSize.width-5, screenSize.height-100);
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;
public class BasicSwingTest2 {
private JFrame frame;
protected void initUI() throws MalformedURLException {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
askForPassword();
}
private void askForPassword() {
final JDialog dialog = new JDialog(frame);
dialog.setResizable(false);
BufferedImage myPicture = null;
try {
myPicture = ImageIO
.read(new URL("http://images.all-free-download.com/images/graphiclarge/blue_abstract_background_310971.jpg"));
} catch (IOException e1) {
e1.printStackTrace();
}
Image dimg = myPicture.getScaledInstance(Toolkit.getDefaultToolkit().getScreenSize().width * 2 / 3, Toolkit.getDefaultToolkit()
.getScreenSize().height * 2 / 3, Image.SCALE_SMOOTH);
JLabel picLabel = new JLabel(new ImageIcon(dimg));
picLabel.setLayout(new GridBagLayout());
final JPasswordField password = new JPasswordField(25);
password.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Password is " + new String(password.getPassword()));
dialog.setVisible(false);
}
});
picLabel.add(password);
dialog.add(picLabel);
dialog.setTitle("Enter your password");
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new BasicSwingTest2().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}
Related
I'm trying to code an app using JFrame. But I have encountered an issue when trying to check if the window is full screen or not. I want my button to be in the same position when it's full and half screen. Here's my code.
package App.Gui;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import App.Gui.Event.ExitEvent;
public class WindowSettings {
private final static ImageIcon imageIcon = new ImageIcon("C:\\Users\\zeesh\\FirstApp\\src\\image\\Untitled.png");
public static void setWindow() {
JFrame frame = new JFrame("Debug Configurations");
JPanel panel = new JPanel();
frame.getContentPane();
JButton button = new JButton("X");
Dimension size = button.getPreferredSize();
button.setBounds(1125, 20, 50, 50);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ExitEvent.exit();
}
});
panel.setLayout(null);
panel.add(button);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.setIconImage(imageIcon.getImage());
frame.setSize(1200, 750);
frame.setVisible(true);
}
}
Make use of appropriate layouts, for example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
JButton button = new SquareButton("X");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
JPanel topPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.EAST;
gbc.weightx = 1;
gbc.insets = new Insets(20, 50, 20, 50);
topPane.add(button, gbc);
add(topPane, BorderLayout.NORTH);
JPanel contentPane = new JPanel(new GridBagLayout());
contentPane.add(new JLabel("Stuff goes here"));
add(contentPane);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1200, 750);
}
}
class SquareButton extends JButton {
SquareButton(String s) {
super(s);
}
#Override
public Dimension getPreferredSize() {
FontMetrics fm = getFontMetrics(getFont());
int stringWidth = fm.stringWidth(getText());
int stringHeight = fm.getHeight();
int size = Math.max(stringHeight, stringWidth);
return new Dimension(size + 22, size + 22);
}
}
}
See Laying Out Components Within a Container for more details
But, wait, you want to overlap the button over the top of the content? Well, that's not that hard...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton button = new SquareButton("X");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.insets = new Insets(20, 50, 20, 50);
add(button, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
JPanel contentPane = new JPanel(new GridBagLayout());
contentPane.setBackground(Color.MAGENTA);
contentPane.add(new JLabel("Stuff goes here"));
add(contentPane, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1200, 750);
}
}
class SquareButton extends JButton {
SquareButton(String s) {
super(s);
}
#Override
public Dimension getPreferredSize() {
FontMetrics fm = getFontMetrics(getFont());
int stringWidth = fm.stringWidth(getText());
int stringHeight = fm.getHeight();
int size = Math.max(stringHeight, stringWidth);
return new Dimension(size + 22, size + 22);
}
}
}
I use a JLabel and in front of it a JTextField so that I can represent a defense-like stat with a value. I use the following code:
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
JLabel jl = new JLabel();
ImageIcon ii = new ImageIcon("C:\\Users\\Max\\Desktop\\shield.png");
jl.setIcon(ii);
gbc.gridy = 0;
gbc.gridx = 0;
add(jl, gbc);
gbc.insets = new Insets(5, 10, 10, 10);
JTextField jtf = new JTextField(2);
jtf.setHorizontalAlignment(JTextField.CENTER);
gbc.ipadx = 10;
gbc.ipady = 10;
gbc.gridy = 0;
gbc.gridx = 0;
jtf.setFocusable(false);
add(jtf, gbc);
And get:
Everything is fine, however, if I try to resize the window, the JTextField disappears for ever and only the JLabel shows. Why is that so?
There is no relationship between the position of the label and the position of the text field, this means that the label and field are free to move independently of each other
There is a z-ordering issue, components lower in the container order are painted after those higher in the container order (reverse order), meaning that the label is actually getting painted before the shield when the whole container is updated. The reason that it might sometimes work is because components can actually be painted independently of each other, meaning that the textfield could actually get painted without need to notify either the parent container or the label
For example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 10, 10, 10);
JTextField jtf = new JTextField(2);
jtf.setHorizontalAlignment(JTextField.CENTER);
gbc.ipadx = 10;
gbc.ipady = 10;
gbc.gridy = 0;
gbc.gridx = 0;
jtf.setFocusable(false);
add(jtf, gbc);
gbc = new GridBagConstraints();
try {
JLabel jl = new JLabel();
ImageIcon ii = new ImageIcon(ImageIO.read(getClass().getResource("/shield01.png")));
jl.setIcon(ii);
gbc.gridy = 0;
gbc.gridx = 0;
add(jl, gbc);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
A possibly better solution would be to create a "background" component which took an image and painted it as the background of the component and then add your text field to it.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class TestBackground {
public static void main(String[] args) {
new TestBackground();
}
public TestBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
try {
BackgroundPane pane = new BackgroundPane(ImageIO.read(getClass().getResource("/shield02.png")));
pane.setLayout(new GridBagLayout());
pane.setBorder(new EmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
JTextField jtf = new JTextField(2);
jtf.setHorizontalAlignment(JTextField.CENTER);
gbc.ipadx = 10;
gbc.ipady = 10;
gbc.gridy = 0;
gbc.gridx = 0;
jtf.setFocusable(false);
pane.add(jtf, gbc);
add(pane);
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
public class BackgroundPane extends JPanel {
private BufferedImage img;
public BackgroundPane(BufferedImage img) {
this.img = img;
}
#Override
public Dimension getPreferredSize() {
return img != null ? new Dimension(img.getWidth(), img.getHeight()) : super.getPreferredSize();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g.drawImage(img, x, y, this);
}
}
}
}
in my new Java project I have a JFrame in which there is a JLabel set to North with BorderLayout, and below it is an image. The image fits fine on the JFrame, but the JLabel cuts off the top of it. How can I resize this JLabel? I tried setPreferredSize and that didn't work. Help would be appreciated.
Code:
package counter.main;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class FoodCounter {
public static JLabel greet4 = new JLabel("",SwingConstants.CENTER);
public static JLabel message4 = new JLabel();
public static JLabel lclicks4 = new JLabel();
public static JButton buttonClick4 = new JButton("+ Food");
public static int clicks4 = 0;
public static URL food = Main.class.getResource("/counter/main/FoodEating.wav");
public static JButton back = new JButton("Back");
public static JLabel bread;
static JFrame frame = new JFrame("Food Counter"); {
createView();
frame.setSize(500, 100);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.revalidate();
frame.repaint();
}
private void createView() {
final JPanel panelc = new JPanel();
frame.getContentPane().add(panelc);
panelc.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 11));
greet4.setFont(new Font( "Dialog", Font.PLAIN, 18));
greet4.setPreferredSize(new Dimension(40, 20));
panelc.add(message4);
frame.add(back, BorderLayout.WEST);
frame.add(greet4, BorderLayout.NORTH);
back.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
SelectionFrame.frame1.setVisible(true);
}
});
panelc.add(buttonClick4);
panelc.add(lclicks4);
updateCounter();
bread = new JLabel("");
bread.setPreferredSize(new Dimension(64, 64));
Image img = new ImageIcon(this.getClass().getResource("/counter/main/SlicedBread64.png")).getImage();
bread.setIcon(new ImageIcon(img));
frame.getContentPane().add(bread, BorderLayout.EAST);
buttonClick4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clicks4++;
updateCounter();
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(food);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException x) {
x.printStackTrace();
}
}
});
};
private void updateCounter() {
lclicks4.setText(clicks4 + "/100 Food ");
if (clicks4 < 1) {
message4.setText("Click to Begin! -->");
}
if (clicks4 >= 1 && clicks4 < 10) {
message4.setText("Keep Going!");
}
if (clicks4 >= 10 && clicks4 < 50) {
message4.setText("Keep 'em Comin'!");
}
if (clicks4 >= 50 && clicks4 < 70) {
message4.setText("Don't Stop!");
}
if (clicks4 >= 70 && clicks4 < 80) {
message4.setText("Almost!");
}
if (clicks4 >= 90 && clicks4 < 100) {
message4.setText("Finish Strong!");
}
if (clicks4 >= 100) {
try {
Thread.sleep(3000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.exit(0);
}
}
}
Don't set sizes, preferred sizes or similar issues on components and top-level windows if it can be avoided.
Instead let the GUI size itself by using layout managers smartly and by calling pack() on the top-level window after adding all components and before calling setVisible(true).
Consider putting dummy text into your greet4 JLabel, so that it takes up space when the GUI is packed. Some spaces, " " will likely suffice.
Unrelated recommendations:
Most of your variables should be instance variables, not static variables. Java is structured along object-oriented programming principles for many reasons, but a chief one is to reduce connections and its associated complexity. By using static variables and methods, you remove this benefit and risk creating programs with a high degree of cyclomatic complexity, making debugging difficult.
Likewise for variables declared as public. Prefer to use private fields to help reduce coupling and increase cohesion.
Run long-running code, such as the code that plays your music, in a background thread to avoid tying up the Swing event thread.
Never call Thread.sleep(...) within the Swing Event Dispatch Thread, or EDT, as this will put your entire Swing GUI to sleep.
For example,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class FoodCounter2 extends JPanel {
public static final String IMAGE_PATH = "https://duke.kenai.com/iconSized/duke.gif";
private static final Font TITLE_FONT = new Font("Dialog", Font.PLAIN, 18);
private JLabel titleLabel = new JLabel("Welcome, User", SwingConstants.CENTER);
private JButton backButton = new JButton("Back");
private JButton addFoodButton = new JButton("+ Food");
private JLabel foodCountLabel = new JLabel("0/100 Food");
public FoodCounter2() throws IOException {
URL imgUrl = new URL(IMAGE_PATH);
BufferedImage img = ImageIO.read(imgUrl);
ImageIcon icon = new ImageIcon(img);
JPanel foodPanel = new JPanel(new GridBagLayout());
// JPanel foodPanel = new JPanel();
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(10, 10, 10, 10);
foodPanel.add(new JLabel("Click to Begin! --->"), gbc);
gbc.gridx++;
foodPanel.add(addFoodButton, gbc);
gbc.gridx++;
foodPanel.add(foodCountLabel, gbc);
JPanel centerPanel = new JPanel(new BorderLayout());
titleLabel.setFont(TITLE_FONT);
centerPanel.add(titleLabel, BorderLayout.PAGE_START);
centerPanel.add(foodPanel, BorderLayout.CENTER);
setLayout(new BorderLayout());
add(backButton, BorderLayout.LINE_START);
add(centerPanel, BorderLayout.CENTER);
add(new JLabel(icon), BorderLayout.LINE_END);
}
private static void createAndShowGui() {
FoodCounter2 mainPanel = null;
try {
mainPanel = new FoodCounter2();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("FoodCounter2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which displays as:
This is what is happening:
As you can see, the top part of the bread is cut off. This is because the JPanel is covering it I assume.
I have 2 buttons, one named btnShort and one named btnLong. I'd like them to be of the same width, so what would be the best option?
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestCode2 {
public static void main(String[] args) {
JFrame window = new JFrame("Test2");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 200);
// ---------------------------------------------------------------------
GridBagLayout layout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
JPanel container = new JPanel(layout);
window.add(container);
constraints.gridy = 0;
JButton btnShort = new JButton("Short");
layout.setConstraints(btnShort, constraints);
container.add(btnShort);
constraints.gridy = 1;
JButton btnLong = new JButton("That's a long button");
layout.setConstraints(btnLong, constraints);
container.add(btnLong);
//This one won't work because button dimension is not known yet...
//btnShort.setPreferredSize(new Dimension(btnLong.getWidth(), btnLong.getHeight()));
// ---------------------------------------------------------------------
window.setVisible(true);
}
}
Set the GridBagConstraints fill property to GridBagConstraints.HORIZONTAL so that both JButton components occupy equal width in the container
constraints.fill = GridBagConstraints.HORIZONTAL;
Make use of an appropriate layout manager, like GridBagLayout and it's constraints...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Buttons {
public static void main(String[] args) {
new Buttons();
}
public Buttons() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new JButton("I'm a very long button"), gbc);
add(new JButton("I'm not"), gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
I don't know why my scroll bar in text area doesn't work. I found many solutions in internet, but no 1 helped for me.
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
I found that can't be Panel's layout Absolute, if I change It to Group layout the same.
What's wrong? Could you help me? Thank you.
UPDATED:
package lt.kvk.i3_2.kalasnikovas_stanislovas;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTextPane;
import javax.swing.DropMode;
import javax.swing.JFormattedTextField;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JMenuItem;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import java.awt.SystemColor;
import java.awt.Font;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.JScrollBar;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JToolBar;
public class KDVizualizuotas {
private JFrame frmInformacijaApieMuzikos;
private JTextField txtStilius;
private JTextArea textArea1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KDVizualizuotas window = new KDVizualizuotas();
window.frmInformacijaApieMuzikos.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public KDVizualizuotas() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmInformacijaApieMuzikos = new JFrame();
frmInformacijaApieMuzikos.setResizable(false);
frmInformacijaApieMuzikos.setIconImage(Toolkit.getDefaultToolkit().getImage(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/Sidebar-Music-Blue-icon.png")));
frmInformacijaApieMuzikos.setTitle("Muzikos stiliai");
frmInformacijaApieMuzikos.setBounds(100, 100, 262, 368);
frmInformacijaApieMuzikos.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txtStilius = new JTextField();
txtStilius.setBounds(10, 34, 128, 20);
txtStilius.setColumns(10);
JButton btnIekoti = new JButton("Ie\u0161koti");
btnIekoti.setBounds(146, 36, 89, 19);
btnIekoti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// textArea1.append(txtStilius.getText()+"\n");
// txtStilius.getText();
Scanner input = new Scanner(System.in);
try {
FileReader fr = new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Stiliai.txt");
BufferedReader br = new BufferedReader(fr);
String stiliuSarasas;
while((stiliuSarasas = br.readLine()) != null) {
System.out.println(stiliuSarasas);
textArea1.append(stiliuSarasas+"\n");
}
fr.close();
}
catch (IOException e) {
System.out.println("Error:" + e.toString());
}
}
});
JPanel panel = new JPanel();
panel.setBounds(10, 65, 224, 243);
panel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panel.setBackground(SystemColor.text);
JLabel lblveskiteMuzikosStili = new JLabel("\u012Eveskite muzikos stili\u0173:");
lblveskiteMuzikosStili.setBounds(10, 14, 222, 14);
frmInformacijaApieMuzikos.getContentPane().setLayout(null);
panel.setLayout(null);
frmInformacijaApieMuzikos.getContentPane().add(panel);
JLabel lblInformacijaApieMuzikos = new JLabel("Informacija apie muzikos stili\u0173:");
lblInformacijaApieMuzikos.setBounds(12, 3, 190, 14);
panel.add(lblInformacijaApieMuzikos);
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
frmInformacijaApieMuzikos.getContentPane().add(txtStilius);
frmInformacijaApieMuzikos.getContentPane().add(btnIekoti);
frmInformacijaApieMuzikos.getContentPane().add(lblveskiteMuzikosStili);
JMenuBar menuBar = new JMenuBar();
frmInformacijaApieMuzikos.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
mntmExit.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/exitas.png")));
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmHelp = new JMenuItem("Help");
mnHelp.add(mntmHelp);
JMenu mnAbout = new JMenu("About");
menuBar.add(mnAbout);
JMenuItem mntmAbout = new JMenuItem("About");
mntmAbout.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/questionmark.png")));
mnAbout.add(mntmAbout);
}
}
You need to add the component you want to be contained within the scroll pane to it.
You can do this via the JScrollPane's constructor or JScrollPane#setViewportView method
public class ScrollPaneTest {
public static void main(String[] args) {
new ScrollPaneTest();
}
public ScrollPaneTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JPanel bigPane = new JPanel();
bigPane.setBackground(Color.BLUE);
// This is not recommended, but is used for demonstration purposes
bigPane.setPreferredSize(new Dimension(1024, 768));
JScrollPane scrollPane = new JScrollPane(bigPane);
scrollPane.setPreferredSize(new Dimension(400, 400));
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Updated with proper layout
You should avoid null or absolute layouts, they will only hurt you in the long wrong.
You may also find How to use Scroll Panes of use
public class BadLayout {
public static void main(String[] args) {
new BadLayout();
}
public BadLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField searchField;
private JButton searchButton;
private JTextArea searchResults;
public TestPane() {
setLayout(new BorderLayout());
searchResults = new JTextArea();
searchResults.setLineWrap(true);
searchResults.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(searchResults);
JPanel results = new JPanel(new BorderLayout());
results.setBorder(new EmptyBorder(4, 8, 8, 8));
results.add(scrollPane);
add(results);
JPanel search = new JPanel(new GridBagLayout());
search.setBorder(new EmptyBorder(8, 8, 4, 8));
searchField = new JTextField(12);
searchButton = new JButton("Search");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.insets = new Insets(0, 0, 0, 4);
search.add(searchField, gbc);
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx++;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
search.add(searchButton, gbc);
add(search, BorderLayout.NORTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
}
}