如何在单击按钮时自动调整背景颜色?

时间:2019-05-20 11:18:58

标签: java user-interface

我试图在单击按钮时改写框架上的背景色。为此,我已经使用setBackground()方法三次了,但是问题是..它仅显示第三个指定的颜色setBackground()忽略了前面的两种setBackground()颜色。

if(s.equals("Click here")) {
            this.setBackground(Color.yellow);
            try 
            {
                Thread.sleep(2000);
            } 
            catch(InterruptedException ie) 
            {}
            this.setBackground(Color.cyan);
            try 
            {
                Thread.sleep(2000);
            }
            catch (InterruptedException ie)
            {   }
            this.setBackground(Color.red);         
 }

帮助我找出代码中的错误。

1 个答案:

答案 0 :(得分:2)

您还可以使用Timer:

if(s.equals("Click here")) {

Timer t = new Timer();
Colors colors = new Colors[3] ; 

 colors[0] = Color.yellow;
 colors[1] = Color.cyan;
 colors[2] = Color.red;
 int i = 0 ; 

t.scheduleAtFixedRate(
    new TimerTask()
    {
        public void run()
        {
                     this.setBackground(colors[i]);
                     i++ ;
                     if(i==3)
                     {
                         t.cancel() ; 
                     }
        }
    },
    0,      
    2000);
}