[英]How can I change the background color of my textbox for just a second in Java?
I want to change the color of my textbox to yellow for just a second, but I cant figure out how to. 我想将文本框的颜色更改为黄色仅一秒钟,但是我不知道该怎么做。 This is my code right now, what it is doing is that it just waits a second and give the textbox the second color.
这是我现在的代码,它的作用是等待一秒钟,然后为文本框提供第二种颜色。
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)
}
}
Ps. 附言 I've also tried Thread.sleep(1000);
我也尝试过Thread.sleep(1000); insted of TimeUnit.SECONDS.sleep(1);
安装了TimeUnit.SECONDS.sleep(1);
With your current code, you're putting your entire GUI to sleep, meaning it is frozen and will not show color changes or interact with the user. 使用当前代码,您将使整个GUI处于休眠状态,这意味着它已冻结,不会显示颜色变化或与用户交互。 You should never call
Thread.sleep(...)
or similar code on the Swing event thread for this very reason. 因此, 绝对不要在Swing事件线程上调用
Thread.sleep(...)
或类似的代码。
Use a Swing Timer instead since this was built just for this type of purpose, to provide for time delayed Swing code, either once, or repeatedly. 请改用Swing计时器,因为它是专门为此类目的而构建的,以提供一次或多次延迟的Swing代码。
eg, 例如,
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.