0

I have 2 windows opened in my Java swing program. If I close one window, the programs stops execution. Is there any way not to stop the execution and play with the other window? Please explain with a sample code as I am new to swings. I tried searching in web, but I think I am lacking proper keywords for this.

shriguru nayak
  • 310
  • 1
  • 3
  • 21

3 Answers3

5

You're probably setting your new windows' close operations to EXIT_ON_CLOSE. Look for places where this happens in your code:

JFrame frame = ... ;
// ...
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

And replace EXIT_ON_CLOSE with DISPOSE_ON_CLOSE for all but the window that you want to have exit the application when closed.

Also take a look at the other ON_CLOSE values that you can pass in the setDefaultCloseOperation javadocs.

Brian
  • 17,079
  • 6
  • 43
  • 66
  • *"..for all but the window that you want to have exit the application when closed."* It also works if `DISPOSE_ON_CLOSE` is used for *every* frame. The last window closed will exit the application. This at least applies so long as there are no lingering non-daemon threads. If there are such threads, they should be shut down sensibly. – Andrew Thompson Sep 21 '12 at 22:58
  • @AndrewThompson Not necessarily. This may be true in Windows, but it's not true for every JVM. From the documentation, "When the last displayable window within the Java virtual machine (VM) is disposed of, the VM **may** terminate." (Emphasis added.) It's suggested, but not required, that the application terminates, but it's not guaranteed. I can't think of any off the top of my head that do, but I remember finding a couple of them. – Brian Sep 21 '12 at 23:22
  • 1
    In that case, see my comment re. 'bad practise' above. – Andrew Thompson Sep 21 '12 at 23:37
  • ..actually. Scratch that and read the next sentence of the docs. that links to [AWT threading issues](http://docs.oracle.com/javase/7/docs/api/java/awt/doc-files/AWTThreadIssues.html). It pretty much agrees with me (but says it better). – Andrew Thompson Sep 21 '12 at 23:40
  • @AndrewThompson I stand corrected. :) It's only for Java 5+ that it works this way, but it works nonetheless. The JVM's I'm thinking of must've been 1.4 (we had a couple clients...) so that's where that came from. Thanks for clarifying. Also, I agree, bad practice to have multi-windowed apps. – Brian Sep 21 '12 at 23:47
2

For the dialog you consider not to be be your main window you should ensure that the default close operation does not cause the application to exit:

window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

You probably are extending JFrame, therefore when you close the main window it closes.

Please paste some code for further help.

Pixelapp
  • 193
  • 1
  • 10