Java Reference
In-Depth Information
// Handle button events
public void actionPerformed(ActionEvent e) {
card.next(getContentPane()); // Switch to the next card
}
}
If you run the program the applet should be as shown
below. Click on the button - and the next button will
be displayed.
How It Works
The CardLayout object, card , is created with horizontal and vertical gaps of fifty pixels. In the
init() method for our applet, we set card as the layout manager and add six buttons to the content
pane. Note that we have two arguments to the add() method. Using card layout requires that you
identify each component by some Object . In this case we pass a String object as the second
argument to the add() method. We use an arbitrary string for each consisting of the string " Card " with
the sequence number of the button appended to it.
Within the loop we call the addActionListener() method for each button to identify our applet
object as the object that will handle events generated for the button (such as clicking on it with the
mouse). When you click on a button, the actionPerformed() method for the applet object will be
called. This just calls the next() method for the layout object to move the next component in sequence
to the top. We will look at event handling in more detail in the next chapter.
The argument to the next() method identifies the container as the TryCardLayout object that is
created when the applet starts. The CardLayout class has other methods that you can use for selecting
from the stack of components:
Method
Description
void previous(
Container parent)
Selects the previous component in the container, parent .
void first(
Container parent)
Selects the first component in the container, parent .
void last(
Container parent)
Selects the last component in the container, parent .
void show(
Container parent,
String name)
Selects the component in the container, parent , associated with the
String object, name . This must be one of the String objects
specified when you called the add() method to add components.
Search WWH ::




Custom Search