How to make a JFrame Modal in Swing java

om. picture om. · Sep 26, 2009 · Viewed 142.2k times · Source

I have created one GUI in which I have used a JFrame. How should I make it Modal?

Answer

akf picture akf · Sep 26, 2009

Your best bet is to use a JDialog instead of a JFrame if you want to make the window modal. Check out details on the introduction of the Modality API in Java 6 for info. There is also a tutorial.

Here is some sample code which will display a JPanel panel in a JDialog which is modal to Frame parentFrame. Except for the constructor, this follows the same pattern as opening a JFrame.

final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

Edit: updated Modality API link & added tutorial link (nod to @spork for the bump).