Kaduna
Kaduna

Reputation: 70

Load FXML in initialize()

I'm creating my first JavaFX application, and I'm doing OK so far. I'm just encountering one problem.

For displaying and loading FXML files I'm using a VistaNavigator class found on StackOverflow:

    public static void loadVista(String fxml) {
    try {
        mainController.setVista(
            FXMLLoader.load(
                VistaNavigator.class.getResource(
                    fxml
                )
            )
        );
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I have a ScanController, which receives input from the keyboard and checks a ticket ID based on this input. When the ticket is OK, it loads "scan-success.fxml", otherwise it loads "scan-failure.xml", each of these FXML-files have an own controller. I'm loading the success FXML like this:

VistaNavigator.loadVista(VistaNavigator.VISTA_SCAN_SUCCESS);

This is working great. The Success-FXML page is showing and the ScanSuccessController is loading. In the initialize() method of ScanSuccessController.java I have the following code snippet:

    try {
        Thread.sleep(2000);                 //1000 milliseconds is one second.
        VistaNavigator.loadVista(VistaNavigator.VISTA_SCAN_HOME);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

So I would like to show the success-page for about 2 seconds, and then head back to the home screen (scan-home.fxml with controller ScanHomeController.java) to scan some more tickets. However, when executing this code, just 'nothing' happens, no exception and no change of FXML-file.

When I try to load a new vista after clicking a button (in an EventHandler) it works great.

I can imagine that JavaFX is not able to load a new FXML-file before the controller has been fully initialised, but cannot figure out where to put this line of code..

I hope someone can help me out with this.

Upvotes: 0

Views: 524

Answers (1)

José Pereda
José Pereda

Reputation: 45486

What about this:

@Override
public void initialize(URL url, ResourceBundle rb) {
    Timeline timeline=new Timeline();
    timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(2), 
            e->VistaNavigator.loadVista(VistaNavigator.VISTA_SCAN_HOME)));
    timeline.play();
}

Note that by using a Timeline everything runs in the JavaFX thread.

Upvotes: 2

Related Questions