views:

65

answers:

3

Does exist in the JDialog class a way to prevent that a child window (JDialog) would be displayed more than once when the button from the main window (JFrame) used to open it, is pressed several times? Many thanks in advance!

A: 

You could make the JDialog modal, then the parent window would not react until it is closed.

Or you could initialize the JDialog before, and just make it visible when your button is pressed. Making it visible twice will not display it twice.

Peter Lang
+2  A: 

Yes, and you don't need to make the box modal to do it (although making it modal would be the easiest way).

Simply do something like the following

In your member delcarations:

private final MyDialog dialog = new MyDialog();

In your code:

private void showDialog() {
   dialog.setVisible(true);
   dialog.requestFocus(); // May be needed to bring window to front
}

This will ensure that you only instantiate the box once. Simply call showDialog() whenever the button is pressed.

Jason Nichols
Pete, example code always makes for a better answer, no?
Chris Kannon
+1  A: 

Another way that I've done in the past with Swing is that when the button is pressed the first thing I do is disable the button. Then I use the observable pattern to look at the child window and re-enable the button when the child window is closed. That way if it takes a while to display the child window for some reason the user can't click on it multiple times and mess things up.

SOA Nerd