Java AWTEventListener create custom event listener

Description

Java AWTEventListener create custom event listener



import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

class My implements AWTEventListener{
   public void eventDispatched(AWTEvent evt) {
      if (evt.getID() == WindowEvent.WINDOW_OPENED) {
        ComponentEvent cev = (ComponentEvent) evt;
        if (cev.getComponent() instanceof JFrame) {
          System.out.println("event: " + evt);
          JFrame frame = (JFrame) cev.getComponent();
          System.out.println(frame);
        }//w  w w.ja  v a2 s .  c  om
      }
    }
} 

public class Main {
  public static void main(String[] args) throws Exception {
    Toolkit tk = Toolkit.getDefaultToolkit();
    final Main main = new Main();

    tk.addAWTEventListener(new My(), AWTEvent.WINDOW_EVENT_MASK);

    final JFrame frame = new JFrame("");
    frame.setName("your frame");
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }

}



PreviousNext

Related