Java Reference
In-Depth Information
The
ActionListener
interface includes only one method:
public void actionPerformed(Action evt) {
// more to come
}
This method is called when a component being listened to generates an action event. In
the
SurveyPanel
class, this happens whenever a button is clicked.
In
SurveyPanel
, this method uses an instance variable that keeps track of which card to
display:
int currentCard = 0;
Every time a button is clicked and
actionPerformed()
is called, this variable is incre-
mented, and the card layout manager's
show(
Container
,
String
)
method is called to
display a new card. If the last card has been displayed, the Finish button is disabled.
Here's the complete method:
public void actionPerformed(ActionEvent evt) {
currentCard++;
if (currentCard >= ask.length) {
ask[2].finalButton.setEnabled(false);
}
cards.show(this, “Card “ + currentCard);
}
Listing 11.5 shows the full
SurveyWizard
class.
LISTING 11.5
The Full Text of
SurveyWizard.java
1: import java.awt.*;
2: import java.awt.event.*;
3: import javax.swing.*;
4:
5: public class SurveyWizard extends JPanel implements ActionListener {
6: int currentCard = 0;
7: CardLayout cards = new CardLayout();
8: SurveyPanel[] ask = new SurveyPanel[3];
9:
10: public SurveyWizard() {
11: super();
12: setSize(240, 140);
13: setLayout(cards);
14: // set up survey
15: String question1 = “What is your gender?”;
16: String[] responses1 = { “female”, “male”, “not telling” };