Java Reference
In-Depth Information
20
21
// Create and register anonymous inner-class listener
22 jbtNew.addActionListener(
23 @Override
24
25
26
27
28 );
29
30 jbtOpen.addActionListener(
new
ActionListener() {
31 @Override
32
public void
actionPerformed(ActionEvent e) {
33 System.out.println(
"Process Open"
);
34 }
35 }
36 );
37
38 jbtSave.addActionListener(
39 @Override
40
public void
actionPerformed(ActionEvent e) {
41 System.out.println(
"Process Save"
);
42 }
43 }
44 );
45
46 jbtPrint.addActionListener(
47 @Override
48
public void
actionPerformed(ActionEvent e) {
49 System.out.println(
"Process Print"
);
50 }
51 }
52 );
53 }
54
55
/** Main method */
56
public static void
main(String[] args) {
57 JFrame frame =
new
AnonymousListenerDemo();
58 frame.setTitle(
"AnonymousListenerDemo"
);
59 frame.setLocationRelativeTo(
null
);
// Center the frame
60 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
61
62 frame.setVisible(
true
);
63 }
64 }
new
ActionListener() {
anonymous listener
handle event
public void
actionPerformed(ActionEvent e) {
System.out.println(
"Process New"
);
}
}
new
ActionListener() {
new
ActionListener() {
frame.pack();
The program creates four listeners using anonymous inner classes (lines 22-52). Without
using anonymous inner classes, you would have to create four separate classes. An anony-
mous listener works the same way as an inner class listener. The program is condensed using
an anonymous inner class.
Anonymous inner classes are compiled into
OuterClassName$#.class
, where
#
starts
at
1
and is incremented for each anonymous class the compiler encounters. In this example,
the anonymous inner classes are compiled into
AnonymousListenerDemo$1.class
,
AnonymousListenerDemo$2.class
,
AnonymousListenerDemo$3.class
,
and
AnonymousListenerDemo$4.class
.
Instead of using the
setSize
method to set the size for the frame, the program uses the
pack()
method (line 61), which automatically sizes the frame according to the size of the
components placed in it.
pack()