Skip to content

Instantly share code, notes, and snippets.

@speters33w
Created October 27, 2023 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save speters33w/573aececbc433ea7f43d4b86fb39a9c3 to your computer and use it in GitHub Desktop.
Save speters33w/573aececbc433ea7f43d4b86fb39a9c3 to your computer and use it in GitHub Desktop.
An Example of the Grid Bag Layout in Java
/* Modified from Listing 10-1 in
The Definitive Guide to Java Swing
by John Zukowski.
*/
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutExample {
private static final Insets insets = new Insets(0, 0, 0, 0);
private static final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private static final int width = 500;
private static final int height = 200;
public static void main(final String[] args) {
Runnable runner = () -> {
final JFrame frame = new JFrame("GridBagLayout");
frame.setLocation(
(int) screenSize.getWidth() / 2 - width / 2, (int) screenSize.getHeight() / 2 - height / 2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
JButton button;
// Row One - Three Buttons
button = new JButton("One");
addComponent(frame, button, 0, 0, 1, 1);
button = new JButton("Two");
addComponent(frame, button, 1, 0, 1, 1);
button = new JButton("Three");
addComponent(frame, button, 2, 0, 1, 1);
// Row Two - Two Buttons, Five will consume two rows.
button = new JButton("Four");
addComponent(frame, button, 0, 1, 2, 1);
button = new JButton("Five");
addComponent(frame, button, 2, 1, 1, 2);
// Row Three - Two Buttons
button = new JButton("Six");
addComponent(frame, button, 0, 2, 1, 1);
button = new JButton("Seven");
addComponent(frame, button, 1, 2, 1, 1);
frame.setSize(width, height);
frame.setVisible(true);
};
EventQueue.invokeLater(runner);
}
private static void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight) {
GridBagConstraints gbc =
new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0, 1.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets, 0, 0);
container.add(component, gbc);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment