我试图在设置场景后移动一个矩形,但它似乎不起作用。
我从一个场景开始加载一个文件,该文件用于在单击按钮时创建下一个场景。
@Override
public void start(Stage primaryStage) {
Scene scene = CreateStartScene();
primaryStage.setScene(scene);
// Load Click Event
loadButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select File");
fileChooser.getExtensionFilters().addAll(new ExtensionFilter("Text Files", "*.txt"));
File file = fileChooser.showOpenDialog(null);
if (file != null) {
fileTextField.setText(file.getAbsolutePath());
startButton.setVisible(true);
}
}
});
// Start Click Event
startButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
if (!fileTextField.getText().isEmpty()) {
// Read in maze file
File file = new File(fileTextField.getText());
ReadFile(file);
Scene scene = CreateMainScene();
primaryStage.setScene(scene);
Solve();
} else {
errorLabel.setText("Please select a file");
}
}
});
primaryStage.show();
}
在CreateMainScene方法中,形状被添加到场景中,其中之一就是这个作为实例变量的矩形
private Rectangle current;
添加如下:
current = new Rectangle();
current.setFill(Color.CORNFLOWERBLUE);
current.setWidth(10);
current.setHeight(10);
current.setX(j * 10);
current.setY(i * 10);
pane.getChildren().add(current);
一切正常,但是在解决方法(递归)中,我试图更改该矩形的位置,并暂停半秒。
current.setX(x * 10);
current.setY(y * 10);
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这不起作用。窗口卡住了几秒钟,然后才最终更新。我想显示矩形在移动,但我不知道该怎么做。
最佳答案
您正在 UI 线程上执行所有操作。在等待 UI 线程时,您会阻止它执行任何其他操作。有更干净的解决方案,但这旨在演示根本问题:
// create and start new Thread, so we don't block the UI
new Thread(() -> {
try {
// wait some time on the new Thread
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// give this to the UI system to be executed on the UI
// thread as soon as there are resources
Platform.runLater(() -> {
// do UI stuff
});
}).start();
关于JavaFX - 在运行时移动矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49802640/