5

I have a Java swing launcher program to launch another class (running its main method). Each program has its cancel button to exit itself.

I use System.exit(0); when this cancel button is pressed.

The launcher program does this in actionPerformed:

if (source==carMenuItem) {
    ta.append("Car launched\n");
    TestCar.main(par);

}
if (source==DialogboxMenuItem) {
    ta.append("Dialogbox launched\n");            
    DialogBox.main(par);
}        
if (source==LengthConversionMenuItem) {
    ta.append("LengthConversion launched\n");            
    LengthConversion.main(par);           
}

When I press the program's cancel button, it also closes my launcher program. How can I avoid this situation?

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
hkguile
  • 4,235
  • 17
  • 68
  • 139
  • 1
    See my answer to [Preventing System.exit() from API](http://stackoverflow.com/questions/5401281/preventing-system-exit-from-api/5401319#5401319). – Andrew Thompson Sep 13 '11 at 06:57

4 Answers4

2

System.exit() terminates the VM therefore your initial thread is terminated also, simply return from your main() method.

After reviewing you code: Not all classes are supposed to have a main() method (If not also used standalone). You should consider to call a constructor to create an instance of a class and call a method not named main().

stacker
  • 68,052
  • 28
  • 140
  • 210
2

Or you can use dispose() method in stead of System.exit() :-because System.exit() will terminate the total application it self.

or you can use setVisible() as false.

Rakesh
  • 4,264
  • 4
  • 32
  • 58
2

you have to implements WindowListener and its WindowEvents, example here

another option is setDefaultCloseOperation properly

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

With System.exit you can't. This will terminate the whole JVM and all processes inside it.

Daniel
  • 3,019
  • 1
  • 20
  • 21