Reputation: 163
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?
Upvotes: 4
Views: 4751
Reputation: 438
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)
}
}
Upvotes: 4
Reputation: 51
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
Upvotes: 0