Search code examples
javajpanelgridbaglayout

JFrame Missing Contents GridBagLayout with Panels


I am using NetBeans 8.2 on OSX and when I run my code I get a window that has the proper title, but no components appear. I made sure that all my frames are set to visible, but still the problem persists.

  public Project(){
    setTitle("Panel");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 200);
    setLocationRelativeTo(null);
    setLayout(new GridBagLayout());
    setVisible(true);

    GridBagConstraints layout = new GridBagConstraints();
    layout.gridy = 3;

    JPanel topPanel = new JPanel();
    topPanel.setVisible(true);
    topPanel.setLayout(new GridLayout(2,1));
    topPanel.add(label1);
    topPanel.add(textField1); 

    JPanel midPanel = new JPanel();
    midPanel.setVisible(true);
    midPanel.setLayout(new GridLayout(1,1));
    midPanel.add(button1);

    JPanel bottomPanel = new JPanel();
    bottomPanel.setVisible(true);
    bottomPanel.setLayout(new GridLayout(2,1));
    bottomPanel.add(label2);
    bottomPanel.add(textField2);

    add(topPanel);
    add(midPanel);
    add(bottomPanel);
  }

  public static void main(String[] args) {
    Project1 frame = new Project1();
  }

Solution

  • Take setVisible(true); and make it the last thing you can call in your constructor

    public Project(){
        setTitle("Panel");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 200);
        setLocationRelativeTo(null);
        setLayout(new GridBagLayout());
        //setVisible(true);
        //...
        setVisible(true);
    }
    

    You should also make sure that the UI is been constructed within the context of the Event Dispatching Thread

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                 Project1 frame = new Project1();
            }
        });
    }
    

    That will help prevent some oddities that can occur