Java Swing How to - Dispatch Window Event








Question

We would like to know how to dispatch Window Event.

Answer

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*from w ww  .ja  va  2s  . c o  m*/
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;

public class Main extends JDialog {

  public Main() {
    this.setLayout(new GridLayout(0, 1));
    this.add(new JLabel("Dialog event test.", JLabel.CENTER));
    this.add(new JButton(new AbstractAction("Close") {
      @Override
      public void actionPerformed(ActionEvent e) {
        Main.this.setVisible(false);
        Main.this.dispatchEvent(new WindowEvent(Main.this,
            WindowEvent.WINDOW_CLOSING));
      }
    }));
    this.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent e) {
        System.out.println(e.paramString());
      }
    });
  }

  private void display() {
    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);
  }

  public static void main(String[] args) {
    new Main().display();
    new Thread(new Runnable() {
      @Override
      public void run() {
        for (int i = 0; i < 3; i++) {
          try {
            Thread.sleep(1000);
            System.out.println((i + 1) + "s. elapsed.");
          } catch (InterruptedException e) {
            e.printStackTrace(System.err);
          }
        }
      }
    }).start();
  }
}