in JAVA 1.1, how can a component notify its container about an event? For example, how can a button's container know it was pressed?

John Zukowski

Have the container add itself as an ActionListener to the Button. The simplest way to do this is to subclass Container and override the addImpl method such that as components are added to the container, if they are buttons, attach an ActionListener. The same can be done for the other event types.

[FAQ Manager Note] Something like the following code does this:


import java.awt.*;
import java.awt.event.*;

public abstract class WatcherPanel extends Container 
                implements ActionListener {
  // subclass and override actionPerformed to do
  //   whatever action you want:
  // public void actionPerformed(ActionEvent e) {
  //   System.out.println("Button " + 
  //     e.getSource() + " pressed");
  // }

  protected void addImpl(Component comp, 
                         Object constraint, 
                         int index) {
    super.addImpl(comp, constraint, index);
    if (comp instanceof Button) {
      ((Button)comp).addActionListener(this);
    }
  }
}
Comment and Contribute

 

 

 

 

 


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

 

 

About | Sitemap | Contact