Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a JFrame Modal in Swing java

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

like image 567
om. Avatar asked Sep 26 '09 15:09

om.


People also ask

Does JFrame contain Swing?

The JFrame class is slightly incompatible with Frame . Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame . This is different from the AWT Frame case.

What is modal Java?

Modal dialog box — A dialog box that blocks input to some other top-level windows in the application, except for windows created with the dialog box as their owner. The modal dialog box captures the window focus until it is closed, usually in response to a button press.


2 Answers

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).

like image 174
akf Avatar answered Sep 26 '22 21:09

akf


You can create a class that is passed a reference to the parent JFrame and holds it in a JFrame variable. Then you can lock the frame that created your new frame.

parentFrame.disable();  //Some actions  parentFrame.enable(); 
like image 20
Kamil Avatar answered Sep 25 '22 21:09

Kamil