Java Reference
In-Depth Information
Using the
next()
or
previous()
methods you can cycle through the components repeatedly, since
the next component after the last is the first, and the component before the first is the last.
The
String
object that we supplied when adding the buttons identifies each button and can be used to
switch to any of them. For instance, you could switch to the button associated with "
Card4
" before the
applet is displayed by adding the following statement after the loop that adds the buttons:
card.show(content, "Card4"); // Switch to button "Card4"
This calls the
show()
method for the layout manager. The first argument is the container and the
second argument is the object identifying the component to be at the top.
Using a Grid Layout Manager
A grid layout manager arranges components in a rectangular grid within the container. There are three
constructors for creating
GridLayout
objects:
Constructor
Description
GridLayout()
Creates a grid layout manager that will arrange components
in a single row (that is, a single column per component) with
no gaps between components.
GridLayout(int rows,
int cols)
Creates a grid layout manager that arranges components in a
grid with
rows
number of rows and
cols
number of
columns, and with no gaps between components.
GridLayout(int rows,
int cols,
int hgap,
int vgap)
Creates a grid layout manager that arranges components in a
grid with
rows
number of rows and
cols
number of
columns, and with horizontal and vertical gaps between
components of
hgap
and
vgap
pixels, respectively.
In the second and third constructors shown above, you can specify either the number of rows, or the
number of columns as zero (but not both). If you specify the number of rows as zero, the layout
manager will provide as many rows in the grid as are necessary to accommodate the number of
components you add to the container. Similarly, setting the number of columns as zero indicates an
arbitrary number of columns. If you fix both the rows and the columns, and add more components to
the container than the grid will accommodate, the number of columns will be increased appropriately.
We can try out a grid layout manager in a variation of a previous application:
Try It Out - Gridlocking Buttons
Make the highlighted changes to
TryWindow.java
.
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.border.EtchedBorder;