Coming Events

Coming Events

If you are extending an AWT Component, such as a Canvas to write your own control, then you will probably want it to trigger events that the super class does not handle. It is not hard to add the necessary logic, so lets use an ActionEvent as an example. First your class will need somewhere to keep track of any number of Listeners which may be waiting for the event. There is an ActionListener class for this purpose:

 import java.awt.event.*;    private ActionListener list;

Then you need two methods so that other objects can add and remove themselves from this list:

      public synchronized void addActionListener(ActionListener al) {        list = AWTEventMulticaster.add(list, al);    }    public synchronized void removeActionListener(ActionListener al) {        list = AWTEventMulticaster.remove(list, al);    }

Finally, at the point in your code where you wish to create an event, it needs to be sent to all waiting Listeners:

      if (list != null)        list.actionPerformed(new ActionEvent(this,        ActionEvent.ACTION_PERFORMED, yourCommand));

There are similar classes to ActionListener for all the other event types that you may need, in the java.awt.event package.


Share the Post: