Java Reference
In-Depth Information
Figure 8-6. An example of the BorderLayout in action
As can be seen, the buttons that were added to the “North” and “South” regions have
expanded to fill the region from the far left to the far right of the JFrame ; however, they have
not expanded to fill space above or below the button. The buttons added to the “East” and
“West” have expanded to fill the space above and below the button, but they have not expanded
to fill to the left or right. The button added to the “Center” can expand in all directions.
Caution If more than one component is added to a region, the newest component placed inside the
region is drawn on top of all other previously added components. This often causes confusion when pro-
grammers are first adding components, as it appears that some of their components have been lost. There
is probably no reason why you would ever want to intentionally add two components in the same region.
There are multiple strategies you can use to lay out components in a container and pre-
vent the preceding anomalies. The best, and perhaps easiest, way to control component flow
is to first place all components into a JPanel container and then place the JPanel container
into one of the five BorderLayout areas. Unlike the BorderLayout , the JPanel 's default layout
manager is the FlowLayout . The properties of this particular type of layout are much easier to
deal with than that of the GridBagLayout or even the GridLayout . Every component placed in
the FlowLayout will maintain its suggested size and will flow from left to right.
The FlowLayout also accepts some justification parameters. The constructor FlowLayout
(int index) may be used with one of the following constants in the FlowLayout class:
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEFT
Listing 8-2 uses a JPanel combined with a JFrame container to display three buttons. You
should also try resizing the JFrame to see the effect this has on FlowLayout . Some examples are
shown in Figures 8-7, 8-8, and 8-9.
Search WWH ::




Custom Search