3

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?

Mkey
  • 155
  • 1
  • 4
  • 12
  • Can you show some code? There are a bunch of ways you could do this: save the `primaryStage` to an instance variable, or pass it to the method as a parameter, or, if you have access to another node, call `someNode.getScene().getWindow()`. – James_D Jan 01 '16 at 07:31
  • If you want to get primaryStage, may be it's will be helpful http://stackoverflow.com/a/31651243/3492619 – DaddyRatel Jan 03 '16 at 21:07

2 Answers2

3

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)
    }
}
itsyahani
  • 408
  • 3
  • 13
0

Instead of declaring your Pane/StackPane/BorderPane/etc. inside of the start method, do it inside of your Main Class.

private static Pane somePane = new Pane();

public static void setSomePane(Pane p) {
    somePane = p;
}

public static Pane getSomePane() {
    return somePane;
}

Then if you're trying to get control of what's displayed in the "primary stage" from another class, you could always just set it with...

Main.setSomePane(new Pane());  

Effectively, you have control over the main window because you control what pane it displays.

From that point, if you want true access of the primary stage, you could do as James_D said and call for the main window as shown below...

Main.getRoot().getScene().getWindow();

Hope that helps

Deezee
  • 51
  • 1
  • 9