Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX how to access primaryStage in function outside of start()

I've got my class with the start method in it to start the primaryStage for javaFX.

However I've got another function called change_screen(int n) which will depending on the number passed to it create a new scene and perform primaryStage.setScene() and .show() for that new scene.

The only issue is that primaryStage is declared in the start function so I can't access it in the change_screen() function.

How would I work around this? I've read an entire java text book so I have an understanding of most concepts but it didn't dive too deep into javaFx so I don't know how to handle multiple scenes.

I've got a game where the screen will be different depending on which menu they are viewing so what would be the best way to change scenes around fairly easily? I'd like to use the primaryStage if possible since it's already instantiated and if I'm to believe I understand javaFX if a knew stage is created that's a new window correct?

If my approach is wrong what is the correct way to change through several scenes all in the same window?

like image 604
Mkey Avatar asked Sep 02 '25 16:09

Mkey


1 Answers

Can't you declare a variable outside and assign stage created in start method to it?

public class YourClass extends Application
{
    private Stage stage;

    @Override
    public void start(Stage primaryStage)
    {
        this.stage = primaryStage;
    }

    public void change_screen(int n)
    {
        stage.setScene(otherScene)
    }
}
like image 121
itsyahani Avatar answered Sep 04 '25 12:09

itsyahani