-2

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 ?

1 Answers1

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