Multiple Buttons

Of course it's possible to have more than one button in an applet. Each button that's going to cause an action to be taken, needs to register at least one 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();

  }

}

Previous | Next | Top
Last Modified November 5, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu