Reputation: 1
I am trying to switch scenes without creating a new window. However, the stage that I initialize and set equal to the default primaryStage that JavaFX provides seems to be equal to null outside of the start method.
Here is the code:
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception{
window = primaryStage;
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
window.setTitle("Hello World");
window.setScene(new Scene(root, 1000, 1000));
window.show();
System.out.println(window + "start");
}
public void regEvent()
{
System.out.println(window);
startGame(4,4);
}
private void startGame(int width, int height)
{
System.out.println(window);
board = new Tile[width][height];
grid = new GridPane();
grid.setPadding(new Insets(10,10,10,10));
//individual cell spacing
grid.setVgap(10);
grid.setHgap(10);
for(int x = 0; x< width; x++)
{
for(int y = 0; y< height; y++)
{
board[x][y] = new Tile(x,y);
board[x][y].setText(x + " , " + y);
GridPane.setConstraints(board[x][y], x, y);
grid.getChildren().add(board[x][y]);
}
}
Scene scene = new Scene(grid,1000,1000);
window.setScene(scene);
window.show();
}
When I say "window.setScene(scene)" in the startGame method, a nullpointer exception is thrown. I know that the window Stage is what is causing it, because println-ing window at the beginning of startGame returns null.
This makes no sense to me, because I initialized window at the beginning of this class, and gave it a value before startGame is even called through the start method.
Can anyone tell me how to switch the scene keeping the same stage? That's all I want to do.
Thanks guys!
Upvotes: 0
Views: 1525
Reputation: 196
I just answered this same question that you're having here :
JavaFX Window Changer using FXML
Upvotes: 0