0
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class ChangeOfColor extends javafx.application.Application {

    @Override
    public void start(Stage primaryStage) {
        var rectangle = new Rectangle(200, 200, Color.BLACK);
        var list_of_color = new Color[]{Color.RED, Color.GREEN, Color.BLUE, Color.ORANGE};
        rectangle.setOnMouseClicked((t) -> {
            for (Color color : list_of_color) {
                rectangle.setFill(color);
                System.out.println(10);
            }
        });
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(new Scene(new Pane(rectangle)));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I try to adjust the cycle so that it is not evaluated immediately and the rectangle color changes to orange, but it waits at the end of each loop and the rectangle color changes sequentially.

I was looking for a solution and found three options.

// Add to end of the loop.

// First - Must use try catch.
Thread.sleep(1000);

// Second - Must use try catch.
TimeUnit.MILLISECONDS.sleep(1000);

// Third
var expectedtime = System.currentTimeMillis() + 1000;
while (System.currentTimeMillis() < expectedtime) {
}

But none of them work properly. While 10 is printed in sequence, the color of the rectangle is the same and at the end it immediately changes to orange.

I also tried to use wait(), but when I write at the end of the loop

rectangle.wait(); // Must use try catch.

so 10 is printed once, the rectangle changes to red and the program crashes immediately.

How should I write it correctly, please?

Thank you

Michal Rama
  • 173
  • 1
  • 1
  • 10
  • What is the execution context here? is it `repaint` ?? – Antoniossss Apr 20 '20 at 13:30
  • can you give the code what you are trying to execute – NIKET BHANDARY Apr 20 '20 at 13:34
  • @Antoniossss Yes. I want to create an array of colors and a cycle that will use them sequentially to change the color of the `Rectangle`. I write the 10 just to make sure it does anything at all. It is not essential for the code itself. – Michal Rama Apr 20 '20 at 14:08
  • @NIKETBHANDARY Exactly the code that is at the beginning. I just need to wait 1 second at the end of each loop. – Michal Rama Apr 20 '20 at 14:15
  • 3
    Use a [`Timeline`](https://openjfx.io/javadoc/13/javafx.graphics/javafx/animation/Timeline.html). If you block execution on the FX Application thread in any way, then the FX Application thread can't repaint the scene, and you don't see any of the intermediate updates. See https://stackoverflow.com/questions/9966136/javafx-periodic-background-task – James_D Apr 20 '20 at 15:00

0 Answers0