Java Swing How to - Use GridBagConstraints to layout two components in the same line








Question

We would like to know how to use GridBagConstraints to layout two components in the same line.

Answer

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
//from w w w  .  jav  a2 s  .c  o  m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {

  Main() {

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(500, 500);

    JPanel panel1 = new JPanel(new GridBagLayout());
    JButton b1 = new JButton("button 1"),
    b2 = new JButton("button 2");

    panel1.add(b1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
        GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,
            0, 0, 0), 0, 0));
    panel1.add(b2, new GridBagConstraints(1, 0, 1, 1, 2.0, 0.0,
        GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,
            0, 0, 0), 0, 0));
    add(panel1);
    setVisible(true);
  }
  public static void main(String[] args) {
    new Main();
  }
}