Search code examples
javajavafxmethodsscenestage

Using standalone methods for each scene in JavaFX


I'm trying to use my scene, home, as a scene in start.
However it does not work and instead of getting my 300 x 300, I get a blank 900 x 400 screen. Perhaps it's something very easily detectable but I'm not seeing it?

    private Scene home;
    private Stage window;    

    public Scene home(Scene home) {
        // build my scene
        return home = new Scene(root, 300, 300);
    } 

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setScene(home);
        window.show();
    } 

I'm trying to create my scenes as methods so I can keep them out of start.
The plan is to switch between scenes later by using: btn.setOnAction(e -> window.setScene(anotherScene));, thanks in advance everyone!


Solution

  • You never call the home method. Therefore the home field will remain null which is the value you pass to window.setScene.

    Furthermore I'd call the home method is implemented in a strange way:

    public Scene home(Scene home) {
    

    The parameter is never read.

        return home = new Scene(root, 300, 300);
    

    This assigns the value to the method parameter, not to the scene before it returns the scene, which has no effect, since java is call-by-value.

    You could implement it like this:

    private Scene home;
    private Stage window;    
    
    public Scene home() {
        if (home == null) {
            // build my scene
            home = new Scene(root, 300, 300)
    
            // or maybe do this without testing, if the scene was created before???
        }
        return home;
    } 
    
    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setScene(home()); // use the method here
        window.show();
    }