Bruce
Bruce

Reputation: 3

Thread freezes UI while doing Countdown

I wanted to create a countdown timer using threads(it's what i was told to try).I did make the UI and all but once I add the thread it freezes. I've tried using Thread.yield() but it didn't work. I tried doing the invokeLater() trick I saw in a different question but it keeps giving me cannot convert void to Thread.

After each second passes by the UI is supposed to update the JTextField.

field = new JTextArea();    
Button = new JButton();
Button.addActionListener
(
    new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            for (int i = Integer.parseInt(field.getText()); i >= 0; i--)
            {
                try
                {
                    Thread.sleep(1000);
                }
                field.setText(Integer.toString(i));
            }
        }
    }
);

Upvotes: 0

Views: 100

Answers (2)

Guilherme Campos Hazan
Guilherme Campos Hazan

Reputation: 1031

You're not using threads at all. Try this:

   field = new JTextArea();    
   Button = new JButton();
        Button.addActionListener
        (
            new ActionListener()
            {
                public void actionPerformed(ActionEvent ae)
                {
                    new Thread() {public void run() {
                       for (int i = Integer.parseInt(field.getText()); i >= 0; i--)
                       {
                           try
                           {
                               Thread.sleep(1000);
                           }
                           field.setText(Integer.toString(i));
                       }
                    }}.start();
                }
            }
        );

Upvotes: 1

Curious
Curious

Reputation: 473

"Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors. Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce." - From https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html

Event dispatcher thread is the basics of swing. Use worker threads.

Upvotes: 0

Related Questions