Java Reference
In-Depth Information
public
public class
class
ButtonDemo2b
ButtonDemo2b
extends
extends
Applet
{
Button b1
,
b2
;
ActionListener handler
=
new
new
ButtonHandler
();
public
public
void
void
init
() {
add
(
b1
=
new
new
Button
(
"A button"
));
b1
.
addActionListener
(
handler
);
add
(
b2
=
new
new
Button
(
"Another button"
));
b2
.
addActionListener
(
handler
);
}
class
class
ButtonHandler
ButtonHandler
implements
implements
ActionListener
{
public
public
void
void
actionPerformed
(
ActionEvent e
) {
iif
(
e
.
getSource
() ==
b1
)
showStatus
(
"Thanks for pushing my first button!"
);
else
showStatus
(
"Thanks for pushing my second button!"
);
}
}
}
Note that merely breaking the action handling code into its own class doesn't really contrib-
ute much to readability. But there is a way to use inner classes that does promote readability
and maintainability. We create an inner class (see
Using Inner Classes
)
for each event
source—each button, each menu item, and so on. Sounds like a lot of work, and it would be,
if you used the previous method. But there is a shorter way, using anonymous inner classes,
described next.
Action Handling Using Anonymous Inner Classes
Problem
You want action handling with less creation of special classes.
Solution
Use anonymous inner classes.