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.WindowEvent;
/*from  ww w.j  a  va 2s . com*/
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 close 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));
      }
    }));
  }

  private void display() {
    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    this.pack();
    this.setVisible(true);
  }
  public static void main(String[] args) {
    new Main().display();
  }
}