Search code examples
javamethodsjavafxstage

JavaFX primaryStage.close() from method


I currently have some code that makes a button in the primaryStage that spawns a new stage. My goal is to have the button close the stage it's on using the setOnMouseClicked method right after launching the new one. Here is how it's currently setup:

@Override
public void start(Stage primaryStage) {

    setPlayBtn();

}

private void setPlayBtn() {
    play = new ImageView(new Image(BugWars.class.getResourceAsStream("images/play-btn.png")));
    play.setFitHeight(50);
    play.setFitWidth(50);
    play.setX(375);
    play.setY(375);
    play.setOnMouseClicked(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            setGame(); // This creates the new stage.
            primaryStage.close();

        }
    });

Unfortunately this doesn't work. Netbeans complains that it can't find the symbol. It thinks it's a variable. I'm sure it's something stupid, but any help referencing the primaryStage would be appreciated. Thanks guys!


Solution

  • So I've worked around the problem by simply making the PlayBtn instatiate inside of the start() method that(I believe) creates primaryStage and then making primaryStage final. I don't know why this works, but it does.