Java Swing How to - Make compact grid with resizable JButtons using GridBagLayout








Question

We would like to know how to make compact grid with resizable JButtons using GridBagLayout.

Answer

import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
//  w  w  w.  jav a2 s.c  om
import javax.swing.JFrame;

public class Main extends JFrame {
  public static void main(String[] args) {
    Main app = new Main();
    app.setDefaultCloseOperation(EXIT_ON_CLOSE);
    app.setVisible(true);
  }
  Main() {
    this.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;

    this.add(new Button("Resizable"), c);
    c = new GridBagConstraints();
    c.weightx = 0.0;

    this.add(new Button("Not Resizable"));
    this.pack();
  }
}