Java Reference
In-Depth Information
The button group in the WEST area was first placed into a JPanel with a one-column
GridLayout to give all buttons the same width. This JPanel was then placed into another
JPanel with a FlowLayout so that the grid did not extend over the full height of the WEST
area. The outer JPanel is then inserted into the WEST area of the frame.
Note how the container and the layout manager cooperate in the layout of the components.
The container holds the components, but the layout manager decides their exact arrangement
on screen. Every container has a layout manager. It will use a default layout manager if we do
not explicitly set one. The default is different for different containers: the content pane of a
JFrame , for example, has by default a BorderLayout , whereas JPanels use a FlowLayout
by default.
Exercise 11.18 Look at the GUI of the calculator project used in Chapter 7 (Figure 7.6 on
page 253). What kind of containers/layout managers do you think were used to create it? After
answering in writing, open the calculator-gui project and check your answer by reading the
code.
Exercise 11.19 What kind of layout managers might have been used to create the layout of
BlueJ's editor window?
Exercise 11.20 In BlueJ, invoke the Use Library Class function from the Tools menu.
Look  at the dialog you see on screen. Which containers/layout managers might have
been used to create it? Resize the dialog and observe the resize behavior to get additional
information.
It is time to look again at some code for our ImageViewer application. Our goal is quite sim-
ple. We want to see three components above each other: a label at the top, the image in the mid-
dle, and another label at the bottom. Several layout managers can do this. Which one to choose
becomes clearer when we think about resizing behavior. When we enlarge the window, we
would like the labels to maintain their height and the image to receive all the extra space. This
suggests a BorderLayout : the labels can be in the NORTH and SOUTH areas, and the image
in the CENTER. Code 11.5 shows the source code to implement this.
Two details are worth noting. First, the setLayout method is used on the content pane to set
the intended layout manager. 5 The layout manager itself is an object, so we create an instance of
BorderLayout and pass it to the setLayout method.
Second, when we add a component to a container with a BorderLayout , we use a differ-
ent add method that has a second parameter. The value for the second parameter is one of
the public constants NORTH , SOUTH , EAST , WEST , and CENTER , which are defined in class
BorderLayout .
5
Strictly speaking, the setLayout call is not needed here, as the default layout manager of the content
pane is already a BorderLayout . We have included the call here for clarity and readability.
 
Search WWH ::




Custom Search