Search code examples
javaswinguser-interfacejtextfield

JTextField clears Jframe


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.


Solution

  • 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?