【问题标题】:How can I change the background color of my textbox for just a second in Java?如何在 Java 中将文本框的背景颜色更改一秒钟?
【发布时间】:2014-12-01 21:41:29
【问题描述】:

我想将文本框的颜色更改为黄色一会儿,但我不知道该怎么做。这是我现在的代码,它所做的只是等待一秒钟,然后给文本框提供第二种颜色。

 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)
   }       
}

附言。我也试过 Thread.sleep(1000);插入 TimeUnit.SECONDS.sleep(1);

【问题讨论】:

    标签: java colors background sleep


    【解决方案1】:

    使用您当前的代码,您将整个 GUI 置于睡眠状态,这意味着它被冻结并且不会显示颜色变化或与用户交互。出于这个原因,您应该永远不要在 Swing 事件线程上调用 Thread.sleep(...) 或类似代码。

    请改用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();
    

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 2021-06-10
      • 1970-01-01
      • 2013-03-04
      相关资源
      最近更新 更多