I'm trying to learn JavaFX and I'm having some trouble understanding how the JavaFX thread can interact with the rest of my application. I'm using JavaFX for the interface window but I have some other stuff running in the main thread.
I load my FXML from a file I've created with the Scene Builder and I've attached the open
method to a MenuItem
in Scene Builder.
I've tried having an instance variable in the Editor class and populating it in the constructor as well as the start method but it's always null
in the open
method. As far as I understand this is because the open
method is called from the JavaFX thread. What is the best practice to solve this problem? This goes the other way to, what if I want to access a component if the JavaFX thread in my main thread?
public class Editor extends Application {
private Stage stage;
private FileChooser fileChooser;
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
stage.setTitle("Editx");
stage.setScene(new Scene(
FXMLLoader.load(this.getClass().getResource("./Editor.fxml")),
1280,
800));
stage.show();
this.fileChooser = new FileChooser();
this.fileChooser.getExtensionFilters().add(
new FileChooser.ExtensionFilter("OBJ", "*.obj"));
this.fileChooser.getExtensionFilters().add(
new FileChooser.ExtensionFilter("All Files", "*.*"));
}
@FXML
private void open() {
// Both this.fileChooser and this.stage is null here for example
File file = this.fileChooser.showOpenDialog(this.stage);
}
}