Bruce Bruce - 1 month ago 8
Java Question

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));
}
}
}
);

Answer

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();
                }
            }
        );