Java Swing How to - Create modal JDialog








Question

We would like to know how to create modal JDialog.

Answer

import javax.swing.JDialog;
import javax.swing.JFrame;
/* w  w w  .  j a  va 2 s .  c om*/
public class Main {
  JFrame frame = new JFrame();
  JDialog dialog = new JDialog();

  public Main() {
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
    dialog = new JDialog(frame, true);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setModal(true);
    dialog.setSize(300, 200);
    dialog.setVisible(true);
  }

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