Java Reference
In-Depth Information
TABLE 6-2
Some Methods of the
class
Container
Method / Description
public void
add(Object obj)
//Method to add an object to the pane.
public void
setLayout(Object obj)
//Method to set the layout of the pane.
The
class
Container
is contained in the package
java.awt
. To use this
class
in your
program, you need to include one of the following statements:
import
java.awt.*;
or:
6
import
java.awt.Container;
As noted earlier, the method
setLayout
is used to set the layout of the content pane,
pane
. To set the layout of the container to a grid, you use the
class
GridLayout
.
Consider the following statement:
pane.setLayout(
new
GridLayout(5, 2));
This statement creates an object belonging to the
class
GridLayout
and assigns that
object as the layout of the content pane,
pane
, by invoking the
setLayout
method.
Moreover, this statement sets the layout of the content pane,
pane
, to five rows and two
columns. This allows you to add 10 components arranged in five rows and two columns.
Note that the
GridLayout
manager arranges GUI components in a matrix formation
with the number of rows and columns defined by the constructor and that the compo-
nents are placed left to right, starting with the first row. For example, in the statement
pane.setLayout(
new
GridLayout(5, 2));
, the expression
new
GridLayout(5, 2)
,
invokes the constructor of the
class
GridLayout
and sets the number of rows to 5 and
the number of columns to 2. Also, in this chapter, we only discuss the
GridLayout
manager; additional layout managers are discussed in Chapter 12. Layout managers allow
you to manage GUI components in a content pane.
If you do not specify a layout, Java uses a default layout. If you specify a layout, you must set
the layout before adding any components. Once the layout is set, you can use the method
add
to add the components to the pane; this process is described in the next section.
JLabel
Now you will learn how to create labels and add them to the pane. We assume the
following statements:
Container pane = getContentPane();
pane.setLayout(
new
GridLayout(4, 1));
Search WWH ::
Custom Search