Java Swing How to - Close JDialog from a button








Question

We would like to know how to close JDialog from a button.

Answer

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from   w  w  w  .j ava2 s  .c  o m*/
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;

public class Main extends JFrame implements ActionListener {
  JButton showDialog = new JButton("show dialog");

  public Main() {
    setLayout(new FlowLayout());
    showDialog.addActionListener(this);
    add(showDialog);
    setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    new Dialogz(this, false);
    setEnabled(false);
  }

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

class Dialogz extends JDialog {
  JButton close = new JButton("close");

  public Dialogz(JFrame owner, boolean modal) {
    super(owner, modal);

    add(close);
    setLocationRelativeTo(owner);
    setVisible(true);

    close.addActionListener(e->closez());
  }

  void closez() {
    System.out.println("before =" + getModalityType());
    setModal(true);
    System.out.println("after =" + getModalityType());
    getOwner().setEnabled(true);
    Dialogz.this.dispose();
  }
}