Java Swing How to - Handle JFrame window listener








Question

We would like to know how to handle JFrame window listener.

Answer

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
//from  w w w  .j ava 2  s .  c o m
import javax.swing.JFrame;

public class Main implements WindowListener {
  JFrame window = new JFrame("Window State Listener");

  public Main() {
    window.setBounds(30, 30, 300, 300);
    window.addWindowListener(this);
    window.setVisible(true);
  }

  public static void main(String[] args) {
    new Main();
  }

  public void windowClosing(WindowEvent e) {
    System.out.println("Closing");
    window.dispose();
    System.exit(0);
  }

  public void windowOpened(WindowEvent e) {
    System.out.println("Opened");
  }

  public void windowClosed(WindowEvent e) {
    System.out.println("Closed");
  }

  public void windowIconified(WindowEvent e) {
    System.out.println("Iconified");
  }

  public void windowDeiconified(WindowEvent e) {
    System.out.println("Deiconified");
  }

  public void windowActivated(WindowEvent e) {
    System.out.println("Activated");
  }

  public void windowDeactivated(WindowEvent e) {
    System.out.println("Deactivated");
  }
}