Search code examples
javajpanelnetbeans-8gridbaglayout

Make JPanel to Fill Up Entire Space in GridBagLayout in Java


Design

Refer to the picture above, my Content Panel JPanel Form will change based on which button is clicked on the Navigation Bar Panel. Inside my Content Panel there's a Desktop Pane. This is my code for one of the button:

Panel1 = p1;
Panel2 = p2;
Panel3 = p3;
Panel4 = p4;
Panel5 = p5;

public MainFrame() {
        initComponents();

        GridBagLayout gbLayout = new GridBagLayout();

        p1 = new Panel1();
        p2 = new Panel2();
        p3 = new Panel3();
        p4 = new Panel4();
        p5 = new Panel5();

        desktop.setLayout(gbLayout);
        desktop.add(p1);
        desktop.add(p2);
        desktop.add(p3);
        desktop.add(p4);
        desktop.add(p5);
    }

private void btn1Performed(java.awt.event.ActionEvent evt) {                               
        pnl1.setVisible(true);
        pnl2.setVisible(false);
        pnl3.setVisible(false);
        pnl4.setVisible(false);
        pnl5.setVisible(false);
    } 

I also found out that I can only use GridBagLayout to get this result, but my JPanel Form will not fill up the entire Content Panel, I've also tried changing the layout to Border Layout which I'll get the fill up entire Content Panel result but there will be problem when displaying JPanel Form on button clicks, JPanel Form will not be showing up using Border Layout.


Solution

  • Make JPanel to Fill Up Entire Space in GridBagLayout in Java

    You want to look at GridBagConstraints#weightx, GridBagConstraints#weightxy and GridBagConstraints#fill properties.

    Have a look at How to Use GridBagLayout for more details.

    Based on the operations in btn1Performed, I would however suggest you have a look at How to use CardLayout