Java Swing How to - Do GridBagLayout with GridBagConstraints








Question

We would like to know how to do GridBagLayout with GridBagConstraints.

Answer

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
/*from w w  w . j  a v  a2 s.c  o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

  public static void main(String... args) {
    JPanel contentPane;
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    contentPane = new JPanel();
    contentPane.setLayout(new GridBagLayout());

    JPanel centerPanel = new JPanel();
    centerPanel.setOpaque(true);
    centerPanel.setBackground(Color.CYAN);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.weightx = 1.0;
    gbc.weighty = 0.9;
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 2;
    gbc.fill = GridBagConstraints.BOTH;

    contentPane.add(centerPanel, gbc);

    JButton leftButton = new JButton("Left");
    JButton rightButton = new JButton("Right");
    gbc.gridwidth = 1;
    gbc.gridy = 1;
    gbc.weightx = 0.3;
    gbc.weighty = 0.1;

    contentPane.add(leftButton, gbc);

    gbc.gridx = 1;
    gbc.weightx = 0.7;
    gbc.weighty = 0.1;

    contentPane.add(rightButton, gbc);

    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);

  }
}