Java Reference
In-Depth Information
Every graphical component has a property for its preferred size. By default a com-
ponent's preferred size is just large enough to fit its contents (such as any text or
images inside the component). The FlowLayout allows components to appear in the
frame at their preferred sizes, while the GridLayout disregards its components' pre-
ferred sizes.
If you want to change a component's preferred size, you may set its preferred
size property by calling its setPreferredSize method. For example, the
ComponentsExample program from Section 14.1 created two buttons called
button1 and button2 and set background colors for them. The following modifica-
tion assigns different preferred sizes to the two buttons:
button1.setPreferredSize(new Dimension(150, 14));
button2.setPreferredSize(new Dimension(100, 45));
The frame's FlowLayout respects the buttons' preferred sizes, leading to the fol-
lowing onscreen appearance:
Composite Layouts
The individual layout managers are limited, but it is possible to position components
in complex ways by using multiple layout managers together. Layout managers can
be layered one on top of another to produce combined effects. This is called a
composite layout.
Composite Layout
A layered layout that uses several layout managers in different nested
containers.
A frame acts as a container for components, but it's possible to construct addi-
tional containers and use them to enhance the layout of those components. To create
a composite layout, you'll need to use another type of container called a panel . A
panel is an onscreen component that acts solely as a container for other components
and generally cannot be seen. A panel has its own layout manager that controls the
positions and sizes of any components inside it.
Panels are implemented as objects of the JPanel class. Each JPanel object has a
layout manager, which you can specify either when you construct the panel or by
calling its setLayout method. By creating several panels with different layout man-
agers, you can control how different groups of components will be laid out. You can
then add these panels to the overall frame so that they will appear on the screen.
 
Search WWH ::




Custom Search