Java Swing How to - Create expandable layout with GridBagLayout








Question

We would like to know how to create expandable layout with GridBagLayout.

Answer

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
/*ww w . j  ava  2  s .com*/
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;

public class Main extends JFrame {

  public Main() {
    setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    JPanel panel1 = new JPanel();
    Border eBorder = BorderFactory.createEtchedBorder();

    panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "70pct"));
    gbc.gridx = gbc.gridy = 0;
    gbc.gridwidth = gbc.gridheight = 1;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.weightx = gbc.weighty = 70;
    add(panel1, gbc);

    JPanel panel2 = new JPanel();
    panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "30pct"));
    gbc.gridy = 1;
    gbc.weightx = gbc.weighty = 30;
    gbc.insets = new Insets(2, 2, 2, 2);
    add(panel2, gbc);

    JPanel panel3 = new JPanel();
    panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 2;
    gbc.weightx = 20;
    gbc.insets = new Insets(2, 2, 2, 2);
    add(panel3, gbc);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
  }

  public static void main(String[] args) {
    new Main();
  }
}