Java Reference
In-Depth Information
How It Works
You create the CardLayout object, card , with horizontal and vertical gaps of 50 pixels as a member of
the class because you need to access it in two class methods. In the createAppletGUI() method for the
applet, you set card as the layout manager and add six buttons to the content pane. Note that you have
two arguments to the add() method, the first being the reference to the component you are adding to
the container, the second being a String object to identify the card. Using card layout requires that you
identify each component by an object of some class type and you supply this via the second argument to
the add() method — the method parameter is of type Object . In this example, you pass a String object
as the second argument to the add() method consisting of the string "Card" with the sequence number
of the button appended to it. You could use this string to identify a particular card to be displayed by
calling the show() method for the CardLayout object. For example:
card.show(content, "Card5");
Executing this statement displays the fifth card in content . You could put this statement as the last in the
createAppletGUI() method to see it working.
Within the loop you call the addActionListener() method for each button to identify the applet object
as the object that handles events generated for the button (such as clicking on it with the mouse). You
learn a lot more about action listeners and handling events in the next chapter. When you click on a but-
ton, the actionPerformed() method for the applet object is called. This just calls the next() method
for the layout object to move the next component in sequence to the top. You look at event handling in
much more detail in the next chapter so just accept it for now.
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. They all have a void return type:
previous(Container parent) selects the previous component in parent .
first(Container parent) selects the first component in parent .
last(Container parent) selects the last component in parent .
Search WWH ::




Custom Search