Re: Swing question: How to exit without System.exit()?
Bayless Kirtley <bkirt <at> cox.net>
2006-11-01 01:12:02 GMT
Can't quite agree Tom. I would think it is common to call one swing class
from another. I have dozens of these within the application I am currently
working on. These are not multiple applications but a single one instead.
A few of my classes are also stand alone and many of the others could
well be if desired.
Working in Netbeans, I create most new classes as JFrames. Then, in
the main class, I don't do anything except submit an invocation of the
constructor to the event queue, the code that Netbeans generates. That
way, I can call its constructor from another class and get exactly the same
behavior.
The only difference required for such a JFrame of this sort is that it must
know how it was instantiated. If the class is called from another class I
use a different constructor that set a property telling it that it is not a
stand
alone class. When it is time for the class to exit, I check this property.
If
it was invoked through its main, I call system.exit(). Otherwise, I call
dispose().
This has worked very well for me. In the case of extending a JPanel, I
only do that when it will be used in a JDialog so no main method is ever
needed.
You might give that a try.
Bayless
----- Original Message -----
From: "Tom Ball" <Tom.Ball <at> Sun.COM>
To: <nbusers <at> netbeans.org>
Sent: Tuesday, October 31, 2006 6:21 PM
Subject: Re: [nbusers] Swing question: How to exit without System.exit()?
> Vacuum Joe wrote:
>> I notice that many Swing apps have a Quit button and the action of
>> the Quit button does something like System.exit(0). This is
>> widely-done but it's bad.
>
> Since you are the first person I have heard voice this sentiment in the
> past ten years, I think your view isn't widely held. How about instead
> saying "it doesn't work well with my current design."
>
>> Very few Java classes should ever use
>> System.exit() because it makes it difficult to call them from other
>> apps. In other words, with a well-written Swing app, I should be
>> able to call the main() method of its main class and use it and then
>> quit from it without causing the rest of the JVM to exit.
>
> That's not true, as Swing apps are generally designed to be standalone
> desktop applications, and finishing via System.exit() is what normal
> standalone applications do. What you describe would be better supported
> by applets -- it's fairly easy to write an applet container if you want to
> run multiple applications within a single JVM instance.
>
>> Any suggestions on how to do this?
>
> In theory (as in, I've never tried it), substitute
> Thread.currentThread().interrupt() for System.exit() from within the
> window closing (or any other) event handler.
>
> Tom
>