Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rectangle colouring logic

I have one three rectangles in my canvas. I wanted to change the colours of three rectangles in a slow manner one by one. For example: When starting the application, user should be able to see three rectangles with the same colour (blue). After 2 secons that rectangles colour should change to red. Again after 2 secons the next rectangles colour should get changed. The last one is also done the same way, that means after 2 seconds of the 2nd rectangle.

I wrote in my own way. But it is not working. All the rectanlges are changed together. I want one by one.

Could anyone give me the 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);
                }*/


            }
like image 343
user414967 Avatar asked Nov 29 '25 16:11

user414967


1 Answers

You're likely calling Thread.sleep inside of Swing's event thread or EDT (for event dispatch thread), and this will cause the thread itself to sleep. Since this thread is responsible for all of Swing's graphics and user interactions, this will in effect put your entire application to sleep, and is not what you want to have happen. Instead, read up on and use a Swing Timer for this.

References:

  • Swing Timer tutorial
  • Swing Event Dispatch Thread and Swingworker tutorial

To expand on Hidde's code, you could do:

// 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();
like image 60
Hovercraft Full Of Eels Avatar answered Dec 02 '25 06:12

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!