Java Reference
In-Depth Information
gridBaglayout
The
GridBagLayout
layout manager is one of the most flexible and complex layout managers Java
provides, while still being easy enough to use in a manual manner (
GroupLayout
and
SpringLayout
are even more flexible, but almost impossible to use by hand).
A
GridBagLayout
allows components to be placed in a grid of rows and columns, just like the
GridLayout
manager, but unlike
GridLayout
, cells in a
GridBagLayout
can have different widths
and heights. In addition, it is possible for components to span across cells.
To arrange components, the
GridBagLayout
layout manager bases itself on the preferred sizes
set for each component, as well as a series of so‐called constraints, formulated by means of a
GridBagConstraints
object. Before you read more about these constraints, the following Try It
Out introduces the
GridBagLayout
layout manager.
Creating the pocket Calculator with GridBagLayout
try it out
In this Try It Out, you change your pocket calculator from the previous Try It Out to use
GridBagLayout
to demonstrate the added flexibility of this layout manager.
1.
As always, feel free to create a new project in Eclipse when you want to. Create a class called
GridBagLayoutFrame
with the following content:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class GridBagLayoutFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("GridLayout frame");
frame.getContentPane().setLayout(new GridBagLayout());
Map<String, JButton> buttons = makeButtons(
"7", "8", "9", "0", "4", "5", "6", "C",
"1", "2", "3", "=", "+", "-", "*", "/"
);
JTextField resultBox = new JTextField("*** BATTERY EMPTY ***");
resultBox.setEditable(false);
GridBagConstraints constraints = new GridBagConstraints();
// Add number buttons
Search WWH ::
Custom Search