Laxmikant Revdikar
Laxmikant Revdikar

Reputation: 309

Why the new thread also exits after closing of Swing GUI in Java

Here is the code of my program. Problem is that whenever i close the main GUI My new thread also exits. Which by definition should not because it is not a daemon thread. I am working in eclipse and any help would be appreciated.

public class HomeScreen extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTable table;
    private JTextField textField_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    HomeScreen frame = new HomeScreen();
                    frame.setVisible(true);

                    Thread t = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            while(true){
                                System.out.println("Hello");//This should print "Hello" forever but this thread exits after i close main GUI
                            }
                        }
                    });
                    t.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

Upvotes: 0

Views: 60

Answers (1)

Laxmikant Revdikar
Laxmikant Revdikar

Reputation: 309

Thank you all. I got the trick just added a statement to run thread infinitely

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Upvotes: 2

Related Questions