Inner Classes as Event Listeners

It is common to make an event listener class an inner class. This is most commonly used with custom component subclasses that want to handle their own events.

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);

     // specify that action events sent by this
     // button should be handled by the MultiBeepAction mba
     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