Java Reference
In-Depth Information
37.
// anonymous and on the fly.
38.
downButton.addActionListener( new ActionListener(){
39.
public void actionPerformed(ActionEvent evt){
40.
decrement();
41.
}// actionPerformed
42.
}// ActionListener
43.
);// addActionListener
44.
}
45.
46.
public void increment(){
47.
counter.increment();
48.
valueLabel.setText(""+counter.getValue());
49.
}
50.
51.
public void decrement(){
counter.decrement();
52.
valueLabel.setText(""+counter.getValue());
53.
}
54.
55.
56.
57.
}
9.2.4
Comparison of the four implementation techniques
We have seen four ways to implement a listener: in a separate class (Section 3.4), in
an internal class (Section 9.2.1), as an interface (Section 9.2.2) or as an anonymous
object (Section 9.2.3). The first method is especially suited to beginners with little
experience of using interfaces. It also makes sense if the listener has to manipulate
objects from many classes. Then references to all these classes are passed to the
listener in the constructor, so the listener can access them.
The second method allows the listener to directly access methods and variables
of the class it is defined in. This is suited for applications where the listener has
to manipulate objects from only one class.
The third method completely avoids having to define a listener class of its
own. This is considered a more elegant and efficient way by many authors. For
beginners in graphics programming, however, it is often confusing, and a more
structured approach with separate classes is preferred. It also limits the listener's
range to the class that implements it.
The last method, anonymous listeners, assigns an individual listener to every
component. This saves the trouble of checking which component triggered the
listener. Also this method is not easy for beginners to understand.
Let us remark that philosophical wars are fought about what is the best way to
implement listeners and to introduce them to beginners in graphics programming.
The author's opinion on teaching listeners clearly is to use separate classes in the
beginning. This is based on experience. Starting out with the method described
in Section 9.2.2 or 9.2.3 only makes sense if students are experienced with using
Search WWH ::




Custom Search