ActionListener object. Different
buttons can register different ActionListener objects
or they can share. ActionListeners for buttons can be
of the same or different classes. If two buttons register the same
ActionListener, you normally use the action command to
distinguish between them.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TwoButtons extends Applet {
public void init() {
// Construct the button
Button beep = new Button("Beep Once");
MultiBeepAction mba = new MultiBeepAction();
// add the button to the layout
this.add(beep);
beep.addActionListener(mba);
beep.setActionCommand("1");
Button beepTwice = new Button("Beep Twice");
beepTwice.addActionListener(mba);
beepTwice.setActionCommand("2");
this.add(beepTwice);
}
}
class MultiBeepAction implements ActionListener {
public void actionPerformed(ActionEvent ae) {
int n;
try {
n = Integer.parseInt(ae.getActionCommand());
}
catch (NumberFormatException e) {
n = 1;
}
Toolkit tk = Toolkit.getDefaultToolkit();
for (int i = 0; i < n; i++) tk.beep();
}
}