Java Reference
In-Depth Information
11.5.3
Layout
First, we shall work on the task of adding two text labels to our interface: one at the top that is
used to display the filename of the image currently displayed and one at the bottom that is used
for various status messages.
Creating these labels is easy—they are both simple JLabel instances. We store them in in-
stance fields so that we can access them later to change their displayed text. The only question
is how to arrange them on screen.
A first (naïve and incorrect) attempt could look like this:
Container contentPane = frame.getContentPane();
filenameLabel = new JLabel();
contentPane.add(filenameLabel);
imagePanel = new ImagePanel();
contentPane.add(imagePanel);
statusLabel = new JLabel("Version 1.0");
contentPane.add(statusLabel);
The idea here is simple: we get the frame's content pane and add, one after the other, all three
components that we wish to display. The only problem is that we did not specify exactly how
these three components should be arranged. We might want them to appear next to each other, or
one below the other, or in any other possible arrangement. As we did not specify any layout, the
container (the content pane) uses a default behavior. And this, it turns out, is not what we want.
Swing uses layout managers to arrange the layout of components in a GUI. Each container that
holds components, such as the content pane, has an associated layout manager that takes care of
arranging the components within that container.
Exercise 11.16 Continuing from your last version of the project, use the code fragment
shown above to add the two labels. Test it. What do you observe?
Swing provides several different layout managers to support different layout preferences. The
most important are: FlowLayout , BorderLayout , GridLayout , and BoxLayout . Each of
those is represented by a Java class in the Swing library, and each lays out in different ways the
components under its control.
Here follows a short description of each layout. The key differences between them are the ways
in which they position components and how the available space is distributed between the com-
ponents. You can find the examples illustrated here in the layouts project.
A FlowLayout (Figure 11.6) arranges all components sequentially from left to right. It will
leave each component at its preferred size and center them horizontally. If the horizontal space
is not enough to fit all components, they wrap around to a second line. The FlowLayout can
also be set to align components left or right. Because the components are not resized to fill the
available space, there will be spare space around them if the window is resized.
 
Search WWH ::




Custom Search