Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Advanced
May 29, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.
Tom Yarker
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date