【问题标题】:Rectangle colouring logic矩形着色逻辑
【发布时间】:2012-05-27 05:26:42
【问题描述】:

我的画布中有一个三个矩形。我想改变三个矩形的颜色 以一种缓慢的方式。 例如:启动应用程序时,用户应该能够看到三个具有相同颜色(蓝色)的矩形。 2 秒后,矩形颜色应变为红色。 再次在 2 秒后,下一个矩形颜色应该会改变。 最后一个也以相同的方式完成,这意味着在第二个矩形的 2 秒后。

我以自己的方式写作。但它不起作用。所有的矩形都一起改变。我要一个一个。

谁能给我个逻辑。

final Runnable timer = new Runnable() {

        public void run() {


            //list of rectangles size =3; each contain Rectangle.
            for(int i = 0 ; i < rectangleList.size();i++){

                if(rectangleListt.get(i).getBackgroundColor().equals(ColorConstants.blue)){
                    try {

                        rectangleList.get(i).setBackgroundColor(ColorConstants.yellow);
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    //rectSubFigureList.get(i).setBorder(null);
                }/*else{
                    rectSubFigureList.get(i).setBackgroundColor(ColorConstants.blue);
                }*/


            }

【问题讨论】:

    标签: java swing graphics swt


    【解决方案1】:

    您很可能在 Swing 的事件线程或 EDT(用于事件调度线程)内调用 Thread.sleep,这将导致线程本身进入休眠状态。由于这个线程负责 Swing 的所有图形和用户交互,这实际上会让您的整个应用程序进入休眠状态,这不是您想要发生的事情。相反,请继续阅读并为此使用 Swing Timer。

    参考资料:

    要扩展 Hidde 的代码,您可以这样做:

    // the timer:     
    Timer t = new Timer(2000, new ActionListener() {
         private int changed = 0; // better to keep this private and in the class
         @Override
         public void actionPerformed(ActionEvent e) {
            if (changed < rectangleList.size()) {
                rectangleList.setBackgroundColor(someColor);
            } else {
                ((Timer) e.getSource()).stop();
            }
            changed++;
         }
     });
     t.start();
    

    【讨论】:

    • 是的,使用 ArrayList 会更干净 :)
    【解决方案2】:

    你可以设置一个定时器:

        // declaration: 
        static int changed = 0;
    
        // the timer:     
        Timer t = new Timer(2000, new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
                    // Change the colour here:
                    if (changed == 0) {
                      // change the first one
                    } else if (changed == 1) {
                      // change the second one
                    } else if (changed == 2) {
                      // change the last one
                    } else {
                      ((Timer) e.getSource()).stop();
                    }
                    changed ++;
    
              }
         });
         t.start();
    

    【讨论】:

    • 要不要手动一一检查情况?如果我有 500 个矩形并且需要逐个更改颜色会怎样?所以这种方式是不可能的。请给我一些其他的逻辑..
    • 没错。另外,请注意,我不会编写您的整个程序,请您自己考虑一下。我们在这里只是为了让您朝着正确的方向前进。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    相关资源
    最近更新 更多