Java Reference
In-Depth Information
As an anonymous listener is responsible for only a single button, it gets in-
formed only when this specific button is pressed. There is no need to check which
button it was. Therefore, we can immediately call methods
increment
and
decre-
ment
for the
Up
respectively
Down
button. For other listeners, however, there still
can be different events being triggered by the same component, e.g. for a mouse
listener, one might have to check which mouse button has been used. The use of
anonymous listeners is demonstrated in class
CounterAnonymousPanel
.
File:
its/CounterAnonymousGUI/CounterAnonymousPanel.java
1.
package
its.CounterAnonymousGUI;
2.
3.
import
java.awt.BorderLayout;
4.
import
java.awt.event.ActionEvent;
5.
import
java.awt.event.ActionListener;
6.
import
javax.swing.*;
7.
8.
public class
CounterAnonymousPanel
extends
JPanel{
9.
10.
private
CounterModel counter;
11.
private
JLabel valueLabel;
12.
13.
public
CounterAnonymousPanel() {
14.
counter =
new
CounterModel();
15.
16.
BorderLayout bordLay =
new
BorderLayout();
17.
this
.setLayout(bordLay);
18.
19.
JButton upButton
=
new
JButton("Up");
20.
JButton downButton =
new
JButton("Down");
21.
valueLabel =
new
JLabel(""+counter.getValue(),SwingConstants.CENTER);
22.
23.
this
.add(upButton,BorderLayout.WEST);
24.
this
.add(downButton,BorderLayout.EAST);
25.
this
.add(valueLabel,BorderLayout.CENTER);
26.
27.
//
The listener for the up-button is defined
28.
//
anonymous and on the fly.
29.
upButton.addActionListener(
new
ActionListener(){
30.
public void
actionPerformed(ActionEvent evt){
31.
increment();
32.
}//
actionPerformed
33.
}//
ActionListener
34.
);//
addActionListener
35.
36.
//
The listener for the down-button is defined
Search WWH ::
Custom Search