jToggleButton.setText() not changing text on button

Go To StackoverFlow.com

1

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){}
2012-04-04 21:49
by RJ Anzalone
Here is an example of how to use Swing Timer: http://stackoverflow.com/questions/9662222/making-the-user-wait-using-swing/9662385#966238 - Eng.Fouad 2012-04-04 22:28


2

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

2012-04-04 22:05
by ControlAltDel
+1 definitely use a javax.swing.Timer - mre 2012-04-04 22:15
Okay, thanks! I'll try using the swing time - RJ Anzalone 2012-04-04 22:18
Ads