Java Reference
In-Depth Information
Listing 8-25. A Simple GridLayout Application
import java.awt.*;
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) throws Exception {
JFrame theFrame = new JFrame();
theFrame.setLayout(new GridLayout(2,2));
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.add(new JButton("One"));
theFrame.add(new JLabel("A very long component"));
theFrame.add(new JTextField("Three"));
theFrame.add(new JTextArea("Four\nFive\nSix"));
theFrame.pack();
theFrame.setVisible(true);
}
}
Figure 8-32. Example of GridLayout demonstrating consistent cell sizes
As you can see in Figure 8-32, the width of all components is the same as the width of the
longest component—the JLabel with the contents “A very long component”—and the height
of all components is the same as the height of the tallest component—the JTextArea that con-
tains multiple lines of text.
While this layout can be very useful if most of the components are the same size, it is not
very useful when you have considerable differences in component sizes, as we do in our com-
mon frame. If we were to use the GridLayout , then the space allocated to the labels would be
the same as the space allocated to the largest component—the Database location field.
The GridBagLayout also works on a grid of cells; however, components are allowed to
occupy more than one cell, the width of a column is calculated based on the width of the
widest column that does not span multiple columns, and the height of a row is calculated
based on the height of the tallest component in that row that does not span multiple rows.
We will start off with a simple example that contains the same components as used in
Figure 8-32, but this time we will use the GridBagLayout . Listing 8-26 shows the program that
creates the GUI shown in Figure 8-33.
Search WWH ::




Custom Search