有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在单击按钮时自动洗牌背景色?

我试图在点击按钮时将背景色在一个帧上混洗。。为此,我已经使用了三次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) 个答案

  1. # 1 楼答案

    您还可以使用计时器:

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