0

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);
    }
}
  • This doesn't sound like a threading issue. It's unusual to have your `Application` subclass (with the `start(...)` method) also be your controller. Can you show the code that generated the null pointer exception? – James_D Sep 14 '14 at 15:25
  • I've updated the post with something I tried that caused a `NullPointerException`. I will also try separating my `Application` subclass and my controller. –  Sep 14 '14 at 15:30
  • I managed to solve this specific problem by separating the `Application` subclass and the controller, which allowed me to instantiate a `FileChooser` and using it in the `open` method. But I'm still confused as to how I can inject variables from my main thread into the JavaFX thread (preferably into the controller) and vice versa. –  Sep 14 '14 at 15:44
  • I don't really know what "inject variables from [a thread]" means, unless you are just trying to pass parameters to your controller. In that case, this is a duplicate of [Passing Parameters JavaFX FXML](http://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml) – James_D Sep 14 '14 at 18:44

0 Answers0