Java Reference
In-Depth Information
b1
.
addActionListener
(
this
this
);
setSize
(
300
,
200
);
}
public
public
void
void
actionPerformed
(
ActionEvent event
) {
System
.
out
.
println
(
"Thanks for pushing my button!"
);
}
public
public static
static
void
void
main
(
String
[]
unuxed
) {
new
new
ButtonDemo
().
setVisible
(
true
true
);
}
}
This version does not use an inner class to handle the events but does so itself by directly im-
plementing the
ActionListener
interface. This works for small programs, but as an applica-
tion grows, it quickly becomes unserviceable; how do you sort out which button was
pressed? To solve this problem, we normally use an inner class as the action handler and
have a different class for each button, or at least for each related set of actions. First, let's
write the previous code with two buttons so that you can see what I mean:
public
public class
class
ButtonDemo2a
ButtonDemo2a
extends
extends
Applet
implements
implements
ActionListener
{
Button b1
,
b2
;
public
public
void
void
init
() {
add
(
b1
=
new
new
Button
(
"A button"
));
b1
.
addActionListener
(
this
this
);
add
(
b2
=
new
new
Button
(
"Another button"
));
b2
.
addActionListener
(
this
this
);
}
public
public
void
void
actionPerformed
(
ActionEvent e
) {
iif
(
e
.
getSource
() ==
b1
)
showStatus
(
"Thanks for pushing my first button!"
);
else
else
showStatus
(
"Thanks for pushing my second button!"
);
}
}
Now here is the same program written using a
member inner class
—that is, a class that is a
named part of its containing class: