Wednesday, June 27, 2007

Chapter 12 - The java.awt Package: Layout

Chapter 12: The java.awt Package: Layout

Objectives

This chapter helps you to prepare for the exam by covering the following objectives:

Know what layout managers are and how they are used.

.
A general knowledge of what layout managers are and how they are used to organize
components in containers is required for some exam questions. You should also learn the
advantages of layout managers developing platform-independent GUIs.
Know what layout managers are supported by the AWT.

.
The AWT supports five basic layout managers. You will be required to know what these
layout managers are and be able to identify examples of their use.
Know how to write code using component container and layout manager classes of the
java.awt package to present a GUI with specified appearance and resize the behavior and
distinguish the responsibilities of layout managers from those of containers.

.
This is the key objective of this chapter. Several exam questions require you to know the
basics of how layout managers are used. You need to have some practical experience using
the AWT layout managers to correctly answer these exam questions.
Know how to position components without a layout manager.

.
Although you probably won't get tested on this, knowledge of how to position components
without a layout manager will help you to understand layout managers better and make you
a better Java programmer.
Study Strategies

As you read through this chapter, you should concentrate on the following key items:

.
What classes and interfaces support layouts.
.
How layout managers simplify the process of organizing GUI components.
.
How each layout manager is used.
.
How layouts are displayed by Java.
Chapter Introduction

This chapter covers the classes and interfaces of java.awt that are used to organize the display of
GUI components. Knowledge of these classes and interfaces is essential to developing a Java-based
GUI. As a consequence, you will see quite a few questions about the material covered in this chapter.
Fortunately, this material is not difficult. With some study and a little programming, you should be able to
master this material. If you read through this chapter, compile and run the programs, and master the
review questions, you should have no problem with layout managers on the certification exam.

Working with Layout Managers

The way that Java organizes GUI components within containers differs from traditional windowing
systems like Windows, the MacOS, and the X Window system. These older systems require that
programmers specify the absolute position and size of components within containers. This approach is
OK if you are working with a single windowing system. But Java is platform-independent and is not
confined to an particualr windowing system. Instead, Java's AWT provides the capability to organize
components within containers using relative component sizes and positions.
Java's unique approach uses layout managers, which implement layout policies. Layout policies are
rules for organizing components within a container. A layout manager is an object that carries out the
policy for a particular set of components and containers. Layout managers provide a significant benefit
because you can create a custom GUI without having to worry about the exact size and position of your
GUI elements. It's true that modern visual programming tools simplify this aspect of GUI building;
however, this is still a major consideration when building a platform-independent GUI. You don't have to
worry about how a particular button will look when it is displayed by Netscape Navigator under Linux,
Internet Explorer under Windows 98, or under a Macintosh windows program. Java's layout managers
can make sure that your GUI will be laid out consistently across browsers and windowing systems.

- 204



Note GUI Differences and Layouts Many GUI components differ slightly in size and

appearance across browsers and windowing systems. Java's layout managers

accomodates these differences when they display your GUI on different

platforms.

Note Absolute Positioning and Sizing The AWT will also let you use absolute

positioning and sizing. This is accomplished through a null layout manager.

Using Layouts

The method by which the components of a Container object are organized is determined by an object
that implements the LayoutManager interface. The layout of a Container is specified using the
setLayout() method of the Container class. It passes an object that implements the
LayoutManager interface as a parameter.
The LayoutManager interface provides a set of methods that are implemented by classes that control
the layout of a container. These methods include those that add or remove components from a layout,
calculate the size of the container, and lay out the components of the container. The LayoutManager2interface extends the

LayoutManager interface to deal with constraint-based layouts.

The BorderLayoutClass

The BorderLayout class is used to lay out the GUI components contained in a Container object. It
lays out components along the North, South, East, and West borders of the container and in the center
of the container. The center component gets any space left over from the North, South, East, and West
border components. It is the default layout for Window, Frame, and Dialog objects and provides the
capability to specify the horizontal and vertical gap between the laid-out components and the container.

The CardLayoutClass

The CardLayout class is used to lay out the components of a Container object in the form of a deck
of cards in which only one card is visible at a time. The class provides methods that are used to specify
the first, last, next, and previous components in the container.

The FlowLayoutClass

The FlowLayout class is used to lay out the components of a Container object in a left-to-right, top-
to-bottom fashion. It is the default layout used with Panel and Applet objects. It specifies the
alignment of the components it lays out by the LEFT, CENTER, and RIGHT constants.

The GridLayoutClass

The GridLayout class lays out the components of a Container object in a grid in which all
components are the same size. The GridLayout constructor is used to specify the number of rows
and columns of the grid.

The GridBagLayout Class

The GridBagLayout class lays out the components of a Container object in a grid-like fashion.
Some components may occupy more than one row or column. The GridBagConstraints class
identifies the positioning and resizing parameters of a component contained within an object that is laid
out using a GridBagLayout. The Insets class is used to specify the margins associated with an
object that is laid out using a GridBagLayout object. An Insets object is a representation of the
borders of a container. It specifies the space that a container must leave at each of its edges.

Note Layout Managers and Preferred Sizes Layout managers always try to

accommodate the preferred size of a component, which is the minimal

component size needed to display the component normally. However, when

making a tradeoff between layout policy and preferred size, layout policy always

wins. The preferred size of a component is returned by its

getPreferredSize() method.

The Layouts Applet

The Layouts applet, shown in Listing 12.1, provides an example of using containers and layouts. This
applet is run using the HTML file provided in Listing 12.2. When you run the Layouts applet using
appletviewer, it displays the opening window shown in Figure 12.1. You can click the Border, Flow,
Card, Grid, and GridBag buttons in the top panel to change the layout displayed in the panel below it.
Figures 12.2 through 12.5 show the other layouts that are displayed. When you select the Card layout, a
bottom panel is displayed (see Figure 12.2) containing the First, Last, Next, and Previous buttons.
These buttons move you through the card deck of buttons displayed in the middle panel. Play with the
applet to familiarize yourself with its operation before going on to the next section, which describes how
the Layouts applet works.

- 205



Figure 12.1: An example of a BorderLayout.


Figure 12.2: An example of a CardLayout.

- 206



Figure 12.3: An example of a FlowLayout.


Figure 12.4: An example of a GridLayout.

- 207



Figure 12.5: An example of a GridBagLayout.

Listing 12.1: The Layouts Applet


import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Layouts extends Applet {
Panel[] panels;
Panel currentPanel;
static int border=0;
static int card=1;
static int flow=2;
static int grid=3;
static int gridBag=4;
String[] layouts = {"Border","Card","Flow","Grid","GridBag"};
String[] cards = {"First","Last","Next","Previous"};
Button[] layoutButtons = new Button[layouts.length];
Button[] navigateButtons = new Button[cards.length];
Panel layoutButtonPanel = new Panel();
Panel navigateButtonPanel = new Panel();
public void init(){

setLayout(new BorderLayout());

- 208



setupButtons()
;
add("North",layoutButtonPanel)
;
setupDisplayPanels()
;


}
void setupButtons()
{


for(int i=0;i











How the Layouts Applet Works

The Layouts applet begins by declaring a number of variables for use in the applet. These variables
are used as follows:

.
panels—An array of panels used to hold an example of each of the five layouts
.
currentPanel—Identifies the current panel being displayed
.
border—Constant used to identify a BorderLayout
.
card—Constant used to identify a CardLayout
.
flow—Constant used to identify a FlowLayout
.
grid—Constant used to identify a GridLayout
.
gridBag—Constant used to identify a GridBagLayout
.
layouts—An array of labels for the layout buttons
.
cards—An array of labels for the card navigation buttons
.
layoutButtons—The buttons displayed in the top panel
.
navigateButtons—The buttons displayed in the bottom panel when a CardLayoutis selected
.
layoutButtonPanel—The panel used to display the layout buttons
.
navigateButtonPanel—The panel used to display the card navigation buttons
The init() method sets the applet's layout to a BorderLayout. Note that this layout does not
change. Only the layout of the middle panel is changed by clicking the layout buttons. The init()
method invokes the setupButtons() method to initialize the layout and navigation buttons. It adds
the panel which displays the layout buttons at the top (North) of the applet's display. It then invokes the
setupDisplayPanels() method to set up the panels that are used to display the various layouts.
The setupButtons() method initializes the elements of the layoutButtons and
navigateButtons arrays, sets up their event handlers, and adds the buttons to the
layoutButtonPanel and navigateButtonPanel.
The setupDisplayPanels() method creates each of the five layout panels, lays them out, and adds
buttons to them. The buttons are used for display purposes and do not handle any events. The panels
are indexed by the border, flow, card, grid, and gridBag constants. The gridx, gridy,
gridwidth, and gridheight arrays set up the GridBagConstraints object for the
GridBagLayout. These constraints determine the position and dimension of the objects being laid out.
- 212



The panel with the BorderLayout is the first panel displayed and is added to the center of the applet's
display area.
The switchPanels() method is used to remove the current layout panel being displayed and to add
the new panel identified by the newPanel parameter. The setNavigateButtons parameter
determines whether the card navigation buttons panel is displayed at the bottom of the applet's display
area. The validate() method causes the applet to be laid out and its components to be redisplayed.
The ButtonHandler class provides the event handling for the layout and card navigation buttons. This
event handling is performed by the actionPerformed() method. The layout buttons are handled by
invoking the switchPanels() method to display a new layout panel. The navigation buttons are
handled by invoking the first(),last(),next(), and previous() methods of the CardLayoutclass to display other buttons in the

card deck.

Note
The validate(), invalidate(), and doLayout() methods The
validate(), invalidate() and doLayout() methods can be used to cause
a container to be laid out again. The validate() method is used by the AWT to
cause a container to lay out its subcomponents after the components it contains
have been added to or modified. The invalidate() method causes a
component and all of its containers to be marked as needing to be laid out. The
doLayout() method is used to tell a layout manager to layout a com-ponent.

Layout Managers, Layout Policies, and Containers

The Layouts applet provides a great way to study the interaction between layout managers, layout
policies, and containers. Use appletviewer to display the Layouts applet and resize the appletviewer
window to see how each of the layout managers respond to changes in the container's size. Several
exam questions will require you to be familiar with how a container's layout is updated when the
container is resized.

Absolute Positioning

In the preceding sections, you learned how to use the standard AWT layouts to organize the way GUI
components are displayed within a container. But what if you want to organize your GUI using the
traditional absolute positioning approach. In that case, use a null layout and position and size your
components using absolute values. The setBounds() method of the Component class specifies both
the position and dimensions of the component displayed. Because setBounds() is defined in the
Component class, it can be used with all the Component subclasses.

The Positions Applet

The Positions applet, shown in Listing 12.3, illustrates the use of the null layout. The HTML file
contained in Listing 12.4 is used to display this applet. The applet's display is shown in Figure 12.6.
Note that this GUI organization is not easily supported by any of the standard layouts.

Note
The Origin The upper-left corner of a container is position (0,0). The x
coordinate increases as you move to the right. The y coordinate increases as you
move down.


Figure 12.6: The Positions applet displays GUI components using a null layout.
The Positions applet is short and simple, but it shows how the null layout can be used to produce
custom layouts. Two labels and two buttons are declared and initialized. These buttons and labels

- 213



identify the x, y coordinate at which they are located. The init() method sets the applet's layout to
null, invokes the setBounds() method for each of the labels and buttons, and then adds the labels
and buttons to the applet container. The setBounds() method used in this example takes the
following four parameters:

.
The horizontal position of the component.
.
The vertical position of the component.
.
The component's width.
.
The component's height.
Other variations of the setBounds() method are also available, as described in the API description of
the Component class.
Listing 12.3: The Positions Applet


import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Positions extends Applet {
Label label1 = new Label("Label at (10,10)");
Label label2 = new Label("Label at (100,100)");
Button button1 = new Button("Button at (150,150)");
Button button2 = new Button("Button at (200,200)");
public void init() {

setLayout(null)
;
label1.setBounds(10,10,200,30)
;
label2.setBounds(100,100,200,30)
;
button1.setBounds(150,150,150,30)
;
button2.setBounds(200,200,250,60)
;
add(label1)
;
add(label2)
;
add(button1)
;
add(button2)
;


}

}
- 214



Listing 12.4: An HTML File Displaying the Positions Applet













Chapter Summary

This chapter covered the classes and interfaces of java.awt that are used to layout GUI components.
You were introduced to each of the AWT layout managers and learned how they work through a
programming example. You also learned how components are laid out in the absence of a layout
manager. You should now be prepared to test your knowledge of these topics. The following review
questions and exam questions will let you know how well you understand this material and will give you
an idea of how you'll do in related exam questions. They'll also indicate which material you need to
study further.

Key Terms

.
Layout
.
Layout manager
.
Border layout
.
Card layout
.
Flow layout
.
Grid layout
.
Gridbag layout
.
Gridbag constraint
.
Inset
.
Absolute positioning
Review Questions

1.
What is a layout manager?
2.
What advantage do Java's layout managers provide over traditional windowing
systems?
3.
What are the problems faced by Java programmers who don't use layout managers?
4.
What method is used to specify a container's layout?
5.
How are the elements of a BorderLayout organized?
6.
How are the elements of a CardLayout organized?
7.
How are the elements of a FlowLayout organized?
- 215



8. How are the elements of a GridLayout organized?
9. How are the elements of a GridBagLayout organized?
10. Which containers use a BorderLayout as their default layout?
11. Which containers use a FlowLayout as their default layout?
12. What is the preferred size of a component?
Exam Questions
1. The following is an example of which layout?
A. CardLayout
B. nullLayout
C. BorderLayout
D. SetLayout
2. The follwowing is an example of which layout?
A. CardLayout
B. null Layout
C. BorderLayout
D. SetLayout
3. The following is an example of which layout?
- 216



A. GridLayout
B. FlowLayout
C. GridLineLayout
D. LineLayout
4. The following is an example of which layout?
A. GridLayout
B. null Layout
C. GridBagLayout
D. GridBagConstraintLayout
5. The following is an example of which layout?
A. GridLayout
- 217



B.
null Layout
C.
GridBagLayout
D. GridBagConstraintLayout
6. The following is an example of which layout?
A.
CardLayout
B.
null Layout
C.
BorderLayout
D.
SetLayout
7.
Given a component, comp, and a container, cont, that is organized according to a
BorderLayout, which of the following should be used to add comp to the top of the
container.
A.
addTop(cont,comp);
B.
comp.add("North",cont);
C.
cont.add("North",comp);
D.
cont.addTop(comp);
8.
Given a component, comp, and a container, cont, that is organized according to a
FlowLayout, which of the following should be used to add comp to the container.
A.
cont.add(comp);
B.
comp.add(cont);
C.
cont.addComponent(comp);
D.
cont.addAllComponents();
9.
Which method is used to set the layout of a container?
A.
startLayout()
B.
initLayout()
C.
layoutContainer()
D.
setLayout()
10. Which method returns the preferred size of a component?
A.
getPreferredSize()
B.
getPreferred()
C.
getRequiredSize()
D.
getLayout()
11. Which method sets the size and position of a component?
A.
setBounds()
B.
setSizeAndPosition()
C.
setComponentSize()
D.
setComponent()
12. Which layout should you use to organize the components of a container in a tabular
form?
A.
CardLayout
B.
BorderLayout
C.
FlowLayout
- 218



D.
GridLayout
Answers to Review Questions

1.
A layout manager is an object that is used to organize components in a container.
2.
Java uses layout managers to lay out components in a consistent manner across all
windowing platforms. Since Java's layout managers aren't tied to absolute sizing and
positioning, they are able to accommodate platform-specific differences among
windowing systems.
3.
Without layout managers, Java programmers are faced with determining how their GUI
will be displayed across multiple windowing systems and finding a common sizing and
positioning that will work within the constraints imposed by each windowing system.
4.
The setLayout() method is used to specify a container's layout.
5.
The elements of a BorderLayout are organized at the borders (North, South, East,
and West) and the center of a container.
6.
The elements of a CardLayout are stacked, one on top of the other, like a deck of
cards.
7.
The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
8.
The elements of a GridBad layout are of equal size and are laid out using the squares
of a grid.
9.
The elements of a GridBagLayout are organized according to a grid. However, the
elements are of different sizes and may occupy more than one row or column of the grid.
In addition, the rows and columns may have different sizes.
10. The Window, Frame, and Dialog classes use a BorderLayout as their default layout.
11. The Panel and Applet classes use the FlowLayout as their default layout.
12. The preferred size of a component is the minimum component size that will allow the
component to display normally.

Answers to Exam Questions

1.C
2.A
3.B
4.A
5.C
6.B
7.C. The container's add method is invoked, passing it the orientation and component as arguments.
8.A. The container's add method is invoked, passing it the component as an argument.
9.D
10.A
11.A
12.D. The GridLayout is best if the table elements are of equal size. Otherwise, use a GridBagLayout.

No comments: