Listening to Large Number of Actions


TEA APIs

See also TEA Editor Installation and Description

Sometimes the number of actions raised by Components becomes very large. If you send all these actions to the same ActionListener, the selection time of the right method could be very long, because the program has to match the getActionCommand() String of the ActionEvent with all the possible actionCommand Strings. Using the tea.awt.event.ActionManager may be the solution. Here you find the description of how to use ActionManagers in your applications. The code exposed is taken from the Source Codes of the TETRACTYS Enhanced Apis and is extensively used by the TEA Editor.

Class and Methods

One is the class:

  1. Class tea.awt.event.ActionManager

    This is a class that listens to the actions of a huge number of Components, retrieves the associated ActionListener and dispatches the ActionEvent to it. May be useful when an ActionListener listens to a large number of ActionEvents.

and two the main methods:

  1. public void addActionListener(String cmd, ActionListener al)

    Adds an ActionListener associated with the specified command.

  2. public void setDefaultActionListener(ActionListener al)

    Defines the default ActionListener to be called when the actionCommand is not registered.

How the ActionManager works

ActionManger uses Hashtables to associate every actionCommand to its ActionListener. ActionListeners can be added using the Inner Classes Mechanism. For example

	addActionListener("open",new ActionListener() {
	  public void actionPerformed(ActionEvent e) {
	    textEditor.openDocument();
	  }
	});

The previous example is taken from the tea.awt.frame.editor.MainAction used by tea.awt.frame.editor.TextEditor and links the actionCommand "open" to an ActionListener than calls the method openDocument of textEditor (an instance of TextEditor).

This is the actionPerformed() that implements the ActionListener interface in ActionManager.

	public void actionPerformed(ActionEvent ae) {
	  String cmd = ae.getActionCommand();
	  if(cmd != null) {
	    ActionListener al =
	      (ActionListener)actionListeners.get(ae.getActionCommand())
	    ;
	    if(al != null) {
	      al.actionPerformed(ae);
	    } else if(defaultActionListener != null) {
	      defaultActionListener.actionPerformed(ae);
	    }
	  }
	}

I think that the behaviour of ActionManager is now more clear.

The complete source code is available in the TEA APIs page. Write directly to TETRACTYS Freeware for any question or suggestion.


TETRACTYS Freeware Main Page

In the next Issue Java Tutorials will be

AWT: ActionListeners and Dialogs Data Retrieving

GeoCities