Java Reference
In-Depth Information
45.
valueLabel.setText(""+counter.getValue());
46.
}
47.
48.
//
Method actionPerformed is implemented
49.
//
inside the class CounterPanel.
50.
public void
actionPerformed(ActionEvent evt){
51.
String actionCommand = evt.getActionCommand();
52.
if
(actionCommand.equals("Up")){
53.
increment();
54.
}
55.
else if
(actionCommand.equals("Down")){
56.
decrement();
57.
}
58.
else
{
System.out.println("ERROR: Unexpected ActionCommand");
59.
}
60.
}//
actionPerformed
61.
62.
63.
}
9.2.3
Anonymous listeners
Listeners can also be defined
anonymous
and
on-the-fly
. The syntax for assigning
an anonymous listener to a component
comp
looks like this:
comp.addXXXXXXListener([Whole definition of XXXXXXListener goes here.]);
In our example, we have to implement one listener for each button. The anony-
mous implementation of the listener for the
Up
button then looks like this:
upButton.addActionListener(
// Implementation of the listener begins
new
ActionListener(){
// Implementation of required method begins
public void
actionPerformed (ActionEvent evt){
increment();
}
// End of implementation of actionPerformed
}
// End of implementation of ActionListener
);
//End of method addActionListener
The listener is
anonymous
because it does not receive a name. It is
on-the-fly
because it is placed where the listener is assigned to the button, namely inside
the parentheses of method
addActionListener
.Asthe listener has no name, it
cannot be referenced from anywhere. In particular, it cannot be reused for the
Down
button. Therefore we must define another listener for that button, which we
!
again do as an anonymous listener.
Search WWH ::
Custom Search