Reputation: 2055
I have a Swing UI with certain number of buttons. One button invokes a separate swing class and a new window is opened with new buttons and other features. Now when I am closing this window the original window is also getting closed. I think this is because both the classes have impemented
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
//some code
}
}
Now how to overcome this? A code example or link will be very helpful. Thanks
Upvotes: 3
Views: 701
Reputation: 11
Try using setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
on the parent JFrame.
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
will terminate the application when the last JFrame is closed whereas EXIT_ON_CLOSE
will terminate the application as soon as that JFrame is closed.
Upvotes: 0
Reputation: 3318
It is hard to guess without seeing the code. Perhaps your JFrame
has setDefaultCloseOperation
set to close the application when the window is closed (maybe EXIT_ON_CLOSE
). Have a look at the java doc for more info on this.
From the java doc:
EXIT_ON_CLOSE
(defined inJFrame
): Exit the application using theSystem exit
method. Use this only in applications.
This means that the whole application will close. You do not want that for the second window. You just want the window (not the application) to close.
Upvotes: 6
Reputation: 206
SwingUtilities.invokeLater
has no relation to an application closing. Its purpose is to defer the run
method invocation to when the GUI thread has finished painting and processing current events.
I suggest you to check your code for EXIT_ON_CLOSE
as was already suggested and also for System.exit()
calls.
To answer the comment, since you set EXIT_ON_CLOSE
on both frames, it is the expected behaviour to exit the whole application when you close any of the frames. See Javadoc.
To solve your problem, you need to remove this setDefaultCloseOperation
on the second frame.
Upvotes: 3
Reputation: 285430
I agree with the others, calling your code on the main Swing thread, the EDT or Event Dispatch Thread, by using SwingUtilities.invokeLater
has nothing to do with your problem, and in fact is a good habit of getting in to if there's a risk that by not doing this your code could be called off of the EDT. In other words, if you're showing your other window from code called in a JButton's ActionListener, then there's no need to use SwingUtilities.invokeLater
since the actionPerformed method will be called on the EDT.
Getting back to your problem at hand, I suggest that you make the other window a JDialog -- either modal to the application or not, depending on your need -- rather than a JFrame. Doing this allows you to keep the dialog above the main JFrame and allows you to force the user to deal with your dialog before going back to the main GUI, and prevents the application from closing if the dialog closes.
And to answer your likely next question, yes, JDialogs can hold complex GUI's, as complex as any JFrame.
Upvotes: 1