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