tags:

views:

215

answers:

2
+4  Q: 

JFrame in Java

Hi, I am using a JFrame as a pop-up from a main frame, where the user is supposed to enter some information and then press OK. But the problem is that once this sub-frame has opened up, I want the program to ignore any other signal until the OK button is pressed, similar as how it is done with JOptionPanes. As it is now, you could click the button to open up the sub-frame several times, thus getting several frames, and this is not the intention (it causes a lot of bugs even).

I could solve it with a boolean that is true once the OK button is pressed, but that doesn't seem like a cool way to fix it. I feel there has to be some other way of doing it, seeing as I can see the sought-after effect coming from my JOptionPanes, but can't get to it.

Cheers.

+10  A: 

You need a JDialog with modal = true. From the Javadocs:

modal - specifies whether dialog blocks user input to other top-level windows when shown.

Michael Myers
So there is no way for me to do this with a JFrame?
Mats_SX
Not easily. But there's really no reason to use a JFrame here; a JDialog can do almost anything a JFrame can, it's just not treated as a full window by the operating system. A JDialog is meant for this sort of thing (just a little window to collect some input).
Michael Myers
I shall remember that. The details to the issue is that it's a project for school, and I happen to be the project manager. I haven't myself written that code, I just have to deal with the bug it caused lol. So I assumed that a JFrame was what was to be used, but for future encounters with similar tasks, I'll use the JDialog instead, then.
Mats_SX
+5  A: 

Just change the JFrame to a JDialog.

Then in the constructor use this line:

setModal(true);

Your app will then block until the dialog box is closed.

You might want to look into a JOptionPane.showInputDialog() if your users are simply entering a String.

jjnguy
well, they are entering three different Strings, and there are some requirements on what these Strings are allowed to look like.
Mats_SX
With custom reqs like that you will probably want to make your own custom JDialog
jjnguy
you could still do it with JOptionPane though. the "message" argument to JOptionPane is an Object. if a string, it displays the text of the string, but you can pass a JComponent to get other custom content. But i agree with the "Use a modal JDialog, that's what their for" answer above.
John Gardner