Reputation: 162
I'm trying to move a rectangle after setting the scene, however it doesnt seem to work.
I start with a scene to load a file that is used to create the next scene on button click.
@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();
}
In the CreateMainScene method, shapes are added to the scene, one of which is this rectangle that is an instance variable
private Rectangle current;
which is added like this:
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);
that all works fine, however in the solve method (which is recursive) I'm trying to change the position of that rectangle, and the pause for half a second.
current.setX(x * 10);
current.setY(y * 10);
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This does not work. The window freezes for a few seconds, before finally updating. I want to show the rectangle moving but I cant figure out how to do it.
Upvotes: 0
Views: 189
Reputation: 5823
You are executing everything on the UI thread. While waiting on the UI thread you block it from doing anything else. There are cleaner solutions, but this is meant to demonstrate the underlying problem:
// 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();
Upvotes: 2