Share this page 

Call events on a Frame from a PanelTag(s): AWT


A component on a Panel can easily call events on the parent Frame. This way, we can put all the logic in one place. In this example, a Frame contains 1 button and a Panel with 2 buttons on it. The first button on the Panel will generate an event for the button on the Frame while the second panel button will trigger a request to close the Frame and the application.

[TestEventPanel.java]
import java.awt.*;
import java.awt.event.*;

public class TestEventPanel extends Panel {
  Button b1,b2;
 
  TestEventPanel(){
    super();
    setLayout(new FlowLayout());
    setBackground(new Color(0).black);
    b1 = new Button("call event on the frame");
    add(b1);
    b2 = new Button("close the parent frame");
    add(b2);
  }
}
The Frame after adding the Panel, will act as an ActionListener for events for the 2 Panel buttons.

[TestEventFrame.java]
import java.awt.*;
import java.awt.event.*;

public class TestEventFrame extends Frame implements 
     ActionListener, WindowListener  {
 TestEventPanel p1;
 Button b1;
 
 TestEventFrame(String title){
  super(title);
  setLayout(new FlowLayout());
  p1 = new TestEventPanel();
  
  b1 = new Button("A dummy button");
  add(b1);
  
  // the Panel with 2 buttons on it
  add(p1);
  createFrame();
  
  // add the actionlistener
  b1.addActionListener(this);
  p1.b1.addActionListener(this);
  p1.b2.addActionListener(this);
  addWindowListener(this);
 }

 void createFrame() {
  Dimension d = getToolkit().getScreenSize();
  setLocation(d.width/4,d.height/3);
  setSize(400,100);
  setVisible(true);
 }

 public void actionPerformed(ActionEvent ae){
 
  if (ae.getSource()==p1.b1) {
     System.out.println(ae.getActionCommand());  
     ActionEvent new_ae = 
         new ActionEvent (b1,
              ActionEvent.ACTION_PERFORMED, 
              "Panel b1 is calling the dummy button");
     b1.dispatchEvent (new_ae);
  }
     
  if (ae.getSource()==b1) {
     System.out.println("dummy receive :" + ae.getActionCommand());  
  }  
     
  if (ae.getSource()==p1.b2) {
     System.out.println(ae.getActionCommand());  
     processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
  }
     
 }
  
 public void windowClosing(WindowEvent e) { 
   this.dispose(); 
   System.exit(0);
 } 
 public void windowActivated(WindowEvent e) { }
 public void windowDeactivated(WindowEvent e) { }
 public void windowDeiconified(WindowEvent e) { }
 public void windowClosed(WindowEvent e) { }
 public void windowIconified(WindowEvent e) { }
 public void windowOpened(WindowEvent e) { }  
}
and finally

[Java0268.java]
import java.awt.*;

 public class Java0268 extends java.applet.Applet {
    TestEventFrame myTestEventFrame;
    
  public void init() {
    myTestEventFrame = 
       new TestEventFrame("TestEvent Frame");
    }
}
Try it here.