Rectangular coloring

I have three rectangles on my canvas. I wanted to change the colors of the three rectangles in slow order one by one. For example: when starting the application, the user should be able to see three rectangles with the same color (blue). After 2 seconds, the color of the rectangles should change to red. Again after 2 seconds, the next color of the rectangles should change. The latter is also performed in the same way, which means after 2 seconds the second rectangle.

I wrote in my own way. But that does not work. All recantals change together. I want one by one.

Can anyone give me logic.

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


            }
+3
source share
2 answers

You can set a timer:

    // 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();
+3
source

, Thread.sleep Swing EDT ( ), , . Swing , , . Swing .

:

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();
+4

All Articles