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

     // specify that action events sent by this
     // button should be handled by the MultiBeepAction mba
     Button beepTwice = new Button("Beep Twice");

  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 | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
Last Modified November 5, 1997