Java Swing How to - Handle Window Event








Question

We would like to know how to handle Window Event.

Answer

//  ww w.  j  a va2  s. co  m
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
  public static void main(String[] args) {
    JPanel panel = new JPanel();
    panel.add(new JTextField(10));
    panel.add(new JButton("button"));
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);

    frame.addWindowListener(new WindowAdapter() {
      @Override
      public void windowIconified(WindowEvent wEvt) {
        ((JFrame) wEvt.getSource()).dispose();
      }
      @Override
      public void windowDeactivated(WindowEvent wEvt) {
        ((JFrame) wEvt.getSource()).dispose();
      }
    });
  }
}