在引入发送验证码功能后,想让button的文本动态变化,发现如下方法并不能做到:

int limitSec=10;

while(limitSec>0){

sendyzhm.setEnabled(false);
sendyzhm.setText(limitSec + "秒后再获取");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(UserRegister.class.getName()).log(Level.SEVERE, null, ex);
}
//limittime.setText(limitSec + "秒后再获取");
limitSec--;

}

正确的做法如下:

new Thread(new TimerRunable() {

public void run() {
int limitSec = 10;
while (limitSec > 0) {
yzm.setEnabled(false);
yzm.setText(limitSec + "秒后再获取");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
limittime.setText(limitSec + "秒后再获取");
limitSec--;
System.out.println(limitSec);
}
//倒计时结束
limittime.setVisible(false);
yzm.setEnabled(true);
yzm.setText("发送验证码");

}

}).start();

05-14 02:51