- GridBagLayout is the most complex and most flexible of the layout managers.
- Elements are arranged in a rectangular grid.
- Elements can have different sizes and can occupy multiple rows or columns.
- The position and behavior of each element is specified by an instance of the GridBagConstraints class.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
public class TryGridBagLayout {
static JFrame aWindow = new JFrame("This is a Gridbag Layout");
public static void main(String[] args) {
aWindow.setBounds(30, 30, 300, 300);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
aWindow.getContentPane().setLayout(gridbag);
constraints.weightx = constraints.weighty = 10.0;
constraints.fill = constraints.BOTH;
addButton(" Press ", constraints, gridbag);
constraints.gridwidth = constraints.REMAINDER;
addButton("GO", constraints, gridbag);
aWindow.setVisible(true);
}
static void addButton(String label, GridBagConstraints constraints, GridBagLayout layout) {
Border edge = BorderFactory.createRaisedBevelBorder();
JButton button = new JButton(label);
button.setBorder(edge);
layout.setConstraints(button, constraints);
aWindow.getContentPane().add(button);
}
}