I have a JFrame that includes a working button, along with a label. The program works fine, when I click the button I get a popup message that says "starting." But if I try to add a JTextField, when I run the program the frame is blank, for field, button, or label.
The working code without the field is below.
JFrame frame = new JFrame("Test");
frame.setSize(750,300);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JPanel panel = new JPanel(false);
JLabel label = new JLabel("The Game.");
JButton button = new JButton("Start");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Runs this code when button is pressed
JOptionPane.showMessageDialog(null, "Starting");
}
}
);
button.setContentAreaFilled(true);
button.setEnabled(true);
button.setToolTipText("Starts");
button.setVisible(true);
frame.add(panel);
panel.add(label);
panel.add(button);
Code with the field that does not work is below.
JFrame frame = new JFrame("Test");
frame.setSize(750,300);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JPanel panel = new JPanel(false);
JLabel label = new JLabel("The Game.");
JButton button = new JButton("Start");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Runs this code when button is pressed
JOptionPane.showMessageDialog(null, "Starting");
}
}
);
button.setContentAreaFilled(true);
button.setEnabled(true);
button.setToolTipText("Starts");
button.setVisible(true);
JTextField field = new JTextField("test", 20);
field.setEnabled(true);
field.setVisible(true);
frame.add(panel);
panel.add(label);
panel.add(button);
panel.add(field);
So somehow those 4 lines of code are clearing the frame.
Call frame.setVisible(true)
in the last line(after all components added). You are calling it before adding the components. to frame
if you put
frame.pack(); or
frame.setVisible(true);
at the bottom of the code it works.
Try yo move your: frame.setVisible(true);
as the last statement.
Move
frame.setVisible(true);
as the last call. To find out more information, please check the link below.
Why shouldn't I call setVisible(true) before adding components?
There is no need to explicitly set visible property of button to true. Add your panel to the Container of your frame and simple set the visible property of the fame to true at the end.
frame.getContentPane().add(panel);
....
frame.setVisible(true);
It seems you never made the frame visible at the end. To do this, just put frame.setVisible(true);
at the end.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.