简体   繁体   English

如何在Java中仅一秒钟更改文本框的背景颜色?

[英]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.

相关问题 如何使用彩色按钮作为用户选择从第二个活动更改我的 MainActivity 的背景颜色? - How can I change the background color of my MainActivity from a second activity using colored buttons as user choices? 如何更改Java中无法编辑的JTextPane的背景颜色? - How can I change the background color of an uneditable JTextPane in Java? 如何更改Java小程序的背景颜色? - How can I change te background color of a Java applet? 在第二个活动中单击一个按钮时,如何使用微调器更改主要活动的背景颜色? - How can I change the background color of a Main Activity by using spinner while clicking a button in the Second Activity? 如何在Java中随机更改窗口背景的颜色? - How can I change the colour of my window background randomly in java? 如何更改第二行的背景颜色? - How to change the background color of each second row? 如何在Java中更改标签颜色? - How can I change label color in Java? 如何使用iText使用Java创建背景色至(pdf-)文本 - How can I add a background color to my (pdf-) text using iText to create it with Java 在Java中创建JList,如何更改条目的背景颜色? - Creating a JList in Java, how would I change the background color of a entry? 如何更改我的 Android 应用程序列的背景颜色 - How do I change the background color for a column of my Android app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM