如何强制 Java FX 场景刷新?

Nik*_*pol 3 java animation javafx

我有一个 Java FX 场景,带有一个开始按钮和几个代表地图图块的矩形。我还绘制了一个代表我的探险家的球体(它必须探索地图),但我在运行动画时遇到了困难。

在开始按钮的 OnMouseClicked 处理程序中,我启动了一个用于探索地图的算法,该算法改变了球体的位置和已访问过的图块的颜色。问题是在算法运行时场景不会自行更新,所以我只能看到最终场景的样子(在算法停止运行之后)。如何强制场景更新以便我可以按顺序查看所有颜色更改?

后期编辑:

import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Test extends Application {

private static final double boxOuterSize = 50;
private static final double boxInnerSize = 48;
private static final double boxCornerRadius = 20;

private Stage applicationStage;
private Scene applicationScene;

private static double   sceneWidth  = 1024;
private static double   sceneHeight = 800;
private static HBox     container = new HBox();
private static Group    root = new Group();
private Rectangle[] rectangles = new Rectangle[10];

@Override
public void start(Stage mainStage) throws Exception {

    applicationStage = mainStage;
    container.setSpacing(10);
    container.setPadding(new Insets(10, 10, 10, 10));

    try {
        applicationScene = new Scene(container, sceneWidth, sceneHeight);
        applicationScene.addEventHandler(EventType.ROOT,(EventHandler<? super Event>)this);
        applicationScene.setFill(Color.WHITE);

    } catch (Exception exception) {
        System.out.println ("exception : "+exception.getMessage());
    }

    applicationStage.setTitle("HurtLockerRobot - Tema 3 IA");
    applicationStage.getIcons().add(new Image("icon.png"));
    applicationStage.setScene(applicationScene);

    for(int i=0; i<10; i++) {
        Rectangle r = new Rectangle();
        r.setFill(Color.BLUE);
        r.setX(i * boxOuterSize);
        r.setY(0);
        r.setWidth(boxInnerSize);
        r.setHeight(boxInnerSize);
        r.setArcHeight(boxCornerRadius);
        r.setArcWidth(boxCornerRadius);
        r.setSmooth(true);
        rectangles[i] = r;
        root.getChildren().add(rectangles[i]);
    }

    container.getChildren().add(root);
    Button startButton = new Button("Start");
    startButton.setOnMouseClicked(new EventHandler<Event>() {
        @Override
        public void handle(Event arg0) {
            for(int i=0; i<10; i++) {
                rectangles[i].setFill(Color.RED);
                // TODO: some kind of scene refresh here
            }
        }
    });
    container.getChildren().add(startButton);

    applicationStage.show();
}

public static void main(String[] args) {
    launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)

最初所有的矩形都是蓝色的。我想在这里获得的行为是看到矩形按顺序改变颜色。问题是我只能看到最终结果(所有矩形同时改变它们的颜色)。

Ita*_*iha 5

这是一个老问题,它引起了我的注意,因为这是 JavaFX 新手面临的一个非常普遍的问题。

OP 面临的问题是因为他一次更新所有矩形,而无需等待。

OP 可以通过创建一个新线程来等待,为循环的每次迭代将线程置于睡眠状态估计几秒钟,然后使用Platform.runLater.

@Override
public void handle(Event arg0) {
  new Thread(() -> {
     for(int i=0; i<10; i++) {
       try {
          Thread.sleep(1000); // Wait for 1 sec before updating the color
       } catch (InterruptedException e) {
          e.printStackTrace();
       }
       int finalI = i;
       Platform.runLater(() -> rectangles[finalI].setFill(Color.RED));// Update on JavaFX Application Thread
   }
}).start();
Run Code Online (Sandbox Code Playgroud)

上面的代码片段更像是一种传统的做事方式。如果我们想使用“JavaFX”的做事方式,我们可以通过使用Animation.

下面是一个代码片段,它将x-seconds在更改矩形的颜色之前等待。它不需要任何额外的线程,因为等待是由PauseTransition应用到每个矩形处理的。

startButton.setOnMouseClicked(new EventHandler<Event>() {
    @Override
    public void handle(Event arg0) {
        for(int i=0; i<10; i++) {
            PauseTransition pauseTransition = new PauseTransition(Duration.seconds(i));
            int finalI = i;
            pauseTransition.setOnFinished(event -> rectangles[finalI].setFill(Color.RED));
            pauseTransition.play();
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

它为每个矩形创建一个 PauseTransition,并根据它在数组中的索引,rectangles在更新颜色之前等待相同的秒数。