I'm working in NetBeans. I wanted to make a simple 3-2-1 count down after clicking on a toggle button, displaying the countdown on the button. I'm a bit new to working with anything time related in Java, but the simplest way to make such a simple countdown seemed to be just using Thread.sleep() as below. The program waits 3 seconds as it should and prints the button's text to the command line, however, the text on the button itself does not change. Any idea why this might happen and how to fix it? Thanks!

jToggleButton1.setText("3...");
System.out.println(jToggleButton1.getText());
try{
    Thread.sleep(1000);
}
catch(InterruptedException e){}
jToggleButton1.setText("2...");
System.out.println(jToggleButton1.getText());
try{
    Thread.sleep(1000);
}
catch(InterruptedException e){}
jToggleButton1.setText("1...");
System.out.println(jToggleButton1.getText());
try{
    Thread.sleep(1000);
}
catch(InterruptedException e){}
有帮助吗?

解决方案

Your problem is that you are doing all your operations in the event dispatching thread. So the UI has no chance to update. You need to use a SwingWorker or better yet a swing timer (the one that has an Action callback) to make this work right

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top