Java Swing How to - Use GridBagConstraints one value per step








Question

We would like to know how to use GridBagConstraints one value per step.

Answer

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
/*  ww w .jav  a 2  s  . co 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");
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 1;
    gbc.gridwidth = 1;
    panel1.add(b1, gbc);
    gbc.gridx = 2;
    gbc.gridwidth = 2;
    gbc.fill = gbc.HORIZONTAL; // set fill property to HORIZONTAL
    gbc.weightx = 2.0;
    panel1.add(b2, gbc); // While adding button also add it with gbc
    add(panel1);
    setVisible(true);
  }

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