如何强制Java FX场景刷新?

时间:2013-01-20 09:10:42

标签: 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);
}
}

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

2 个答案:

答案 0 :(得分:3)

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

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

OP可以等待创建一个新线程,在循环的每次迭代中将线程置于休眠状态估计的秒数,然后使用Platform.runLater更新JavaFX应用程序线程上的矩形颜色。

@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();

上述代码段更像是一种传统的做事方式。如果我们想使用&#34; JavaFX&#34;做事方式,我们可以通过使用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();
        }
    }
});

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

答案 1 :(得分:0)

这是因为:

exception : Test cannot be cast to javafx.event.EventHandler

好吧,我不知道怎么会出现Class cast异常。

否则,要延迟,您可以使用Thread.sleep()

<强>更新

使用AnimationTimer创建动画很好,你不需要刷新任何东西。

在这里,我做了一个简短的EG,用FillTransition显示颜色矩形。

<强> CODE:

import javafx.animation.FillTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;


public class NewFXMain1 extends Application {
private static final double boxOuterSize = 50;
private static final double boxInnerSize = 48;
private static final double boxCornerRadius = 20;
private Rectangle rectangles = new Rectangle();

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

@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("rect");


    Button btn = new Button();
    StackPane root = new StackPane();


    Rectangle r = new Rectangle();
    r.setFill(Color.BLUE);
    r.setX(2 * boxOuterSize);
    r.setY(0);
    r.setWidth(boxInnerSize);
    r.setHeight(boxInnerSize);
    r.setArcHeight(boxCornerRadius);
    r.setArcWidth(boxCornerRadius);
    r.setSmooth(true);
    r.localToScene(boxOuterSize, boxOuterSize);
    rectangles = r;

    root.getChildren().add(rectangles);

    btn.setText("display");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
           FillTransition ft = new FillTransition(Duration.millis(3000), rectangles, Color.RED, Color.BLUE);
           ft.setCycleCount(4);
           ft.setAutoReverse(true);
           ft.play();
        }
    });

    root.getChildren().add(btn);
    primaryStage.setScene(new Scene(root, 300, 250));
    primaryStage.show();
  }
}
相关问题