Sin*_*ndi 1 java sleep background colors
我想将我的文本框的颜色更改为黄色一秒钟,但我不知道该怎么做。这是我现在的代码,它正在做的是等待一秒钟并为文本框提供第二种颜色。
for(int i=0;i<2;i++){
if(i==0)
{
textbox1.setBackground(Color.yellow); //Turn textbox yellow (first color)
try {
TimeUnit.SECONDS.sleep(1); //wait 1 second
}
catch (InterruptedException e) {}
}
else if(i==1)
{
textbox1.setBackground(Color.white); //Turn textbox white (second color)
}
}
Run Code Online (Sandbox Code Playgroud)
附言。我也试过 Thread.sleep(1000); 插入 TimeUnit.SECONDS.sleep(1);
使用您当前的代码,您将整个 GUI 置于休眠状态,这意味着它被冻结并且不会显示颜色变化或与用户交互。出于这个原因,您永远不应该Thread.sleep(...)在 Swing 事件线程上调用或类似的代码。
使用Swing Timer代替,因为它专为这种类型的目的而构建,以提供一次或重复的时间延迟 Swing 代码。
例如,
textbox1.setBackground(Color.yellow);
int delayTime = 3 * 1000; // 3 seconds
new Timer(delayTime, new ActionListener() {
public void actionPerformed(ActionEvent e) {
textbox1.setBackground(Color.white);
// stop the timer
((Timer) e.getSource()).stop();
}
}).start();
Run Code Online (Sandbox Code Playgroud)