ptg7068951
192 HOUR 14: Laying Out a User Interface
The following statement creates an Insetsobject:
Insets around = new Insets(10, 6, 10, 3);
The aroundobject represents a container border that is 10 pixels inside the
top edge, 6 pixels inside the left, 10 pixels inside the bottom, and 3 pixels
inside the right.
To make use of an Insetsobject in a container, you must override the con-
tainer’s getInsets()method. This method has no arguments and returns
an Insetsobject, as in the following example:
publicInsets getInsets() {
Insets squeeze = new Insets(50, 15, 10, 15);
returnsqueeze;
}
Figure 14.5 shows how this would change the FlowLayout-managed inter-
face shown in Figure 14.1.
FIGURE 14.5
Using insets to add space around
components.
The container shown in Figure 14.5 has an empty border that’s 15 pixels
from the left edge, 10 pixels from the bottom edge, 15 pixels from the right
edge, and 50 pixels from the top edge.
Laying Out an Application
The layout managers you have seen thus far were applied to an entire
frame; the setLayout()method of the frame was used, and all compo-
nents followed the same rules. This setup can be suitable for some pro-
grams, but as you try to develop a GUI with Swing, you often find that
none of the layout managers fit.
One way around this problem is to use a group of JPanelobjects as con-
tainers to hold different parts of a GUI. You can set up different layout
rules for each of these parts by using the setLayout()methods of each
JPanel. After these panels contain all the components they need to contain,
you can add the panels directly to the frame.
NOTE
AJFramecontainer has a built-
in inset to make room for the
frame’s title bar. When you over-
ridegetInsets()and set your
own values,a low inset value
causes the container to display
components underneath the
title bar.