How to make a modal JFrame?

14,500

Solution 1

How to make a modal JFrame?

Don't. Use a modal JDialog -- that's precisely what they're for. You understand of course that a JDialog can hold a complex GUI, as complex as any held by a JFrame.

We often run into posts like these by folks who use a GUI-builder such as NetBeans to help them create their GUI's, and since the second window's code was created by the builder to extend a JFrame, it's very hard for the programmer to go back and change it to a dialog. The way to fix this is to try to gear your Swing code creation towards creation of JPanels, not top-level windows such as JFrames. This way you could use the created JPanel in a JFrame if desired, a JDialog if desired, a JApplet, or even another JPanel, whatever works best for the situation. This will increase your code's flexibility tremendously.

Solution 2

use JDialog and send the third parameter to its constructor as true (modal)

Share:
14,500
user1016195
Author by

user1016195

Updated on June 04, 2022

Comments

  • user1016195
    user1016195 almost 2 years

    Possible Duplicate:
    How to make a JFrame Modal in Swing java

    I have 2 JFrames one is the main JFrame and the other one is a sub JFrame, and I'm trying to make the main JFrame inaccessible to user interactions when I display the sub JFrame.

  • user1016195
    user1016195 over 12 years
    I am using jframe only. Can you give the code?
  • Hovercraft Full Of Eels
    Hovercraft Full Of Eels over 12 years
    There is no "code" to give as it all depends on how you're trying to do things here. First and foremost -- read the Swing tutorials to see how to code with Swing. Next, show us your code. I would be more than happy to help you work with your code.
  • user1016195
    user1016195 over 12 years
    EmployeeForm sub=new EmployeeForm(); sub.setAlwaysOnTop(true); sub.setVisible(true); this.setEnabled(false);
  • user1016195
    user1016195 over 12 years
    this code help me to make sub frame as modal. But now my problem is how will i set the mainJFrame as the active form after closing the subJFrame?
  • Hovercraft Full Of Eels
    Hovercraft Full Of Eels over 12 years
    Again -- don't use a JFrame -- use a JDialog. What about this advice confuses you?
  • user1016195
    user1016195 over 12 years
    How to add a 'cancel' button in jdialog?
  • MOHAMED FATHEI
    MOHAMED FATHEI over 12 years
    any JButton and in its click event write "this.dispose();"
  • ugo
    ugo about 3 years
    My little contribute: frame.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { frame.requestFocus(); } });