I have a Thread launched when a Jboutton listener event . The thread code is huge and I wish when The user close the Jframe the thread continue to run until finishing (even the Jframe is closed ). What Can I do ?
Asked
Active
Viewed 62 times
-2
-
We need a bit of code to help u. And you should show what you have tried so far. – kai May 14 '14 at 10:29
-
1Post [MCVE](http://stackoverflow.com/help/mcve) – alex2410 May 14 '14 at 10:30
-
2Change the defaultCloseOperation from EXIT_ON_CLOSE to DISPOSE_ON_CLOSE. – MadProgrammer May 14 '14 at 10:34
-
1See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson May 14 '14 at 10:43
1 Answers
0
Setting default close operation of frame from JFrame.EXIT_ON_CLOSE
to JFrame.DISPOSE_ON_CLOSE
seems to do exactly what you want.
Demo:
JFrame frame = new JFrame();
JButton button = new JButton("click me");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(100,100);
frame.add(button);
button.addActionListener((listener)->{
new Thread(()->{
System.out.println("Thread started");
for (int i=0; i<10; i++){
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread ended");
}).start();
});
frame.setVisible(true);
If you click button and close frame you will see that thread created by button will still be working. Application will close after all threads will finish their tasks.

Pshemo
- 122,468
- 25
- 185
- 269