JavaFx 关闭阶段不可预测的行为

JavaFx closing Stages unpredictable behaviour

所以我有一个基于 Hydra 的程序。一个 Window 弹出,当试图关闭它时,它关闭了但是另外两个 windows 弹出了它的位置。有两种方法可以关闭 window,即按关闭按钮或红叉。

我的问题是程序的行为非常不可预测,有时它会关闭它并打开 2 个新的有时它不会关闭也不会打开一个新的。

警告!!!!如果执行此代码,则必须通过任务管理器或 IDE.

终止程序
    @Override
    public void start(Stage stage) throws Exception {
        this.stage = stage;
        this.stage.setTitle("Hail Hydra");
        placeNewHeadRandomly();
        this.stage.setScene(growHead());
        this.stage.setOnCloseRequest(e -> {
            cutOffHead();
        });
        this.stage.show();
    }

    private void placeNewHeadRandomly() {
        // not important for this question but randomly changes windows X and Y.
    }

    private Scene growHead() {
        // not important for this question creates a window with a button that calls cutOffHead();
        VBox vbox = new VBox();
        vbox.setPrefWidth(WINDOW_WIDTH);
        vbox.setPrefHeight(WINDOW_HEIGHT);
        vbox.setAlignment(Pos.CENTER);
        vbox.setSpacing(10);
        Label warning = new Label("Cut off one hydra head, two more will grow back in its place.");
        Button sword = new Button("close");
        sword.setOnAction(e -> cutOffHead());
        vbox.getChildren().addAll(warning, sword);
        return new Scene(vbox);
    }

    private void cutOffHead() {
        this.stage.close();
        try {
            start(new Stage());
            start(new Stage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

你连续调用了start(new Stage()),但是是同一个对象的同一个方法。在 start 的开头,您将参数保存到 this.stage 字段中。因此,第一次调用将第一个 new Stage() 的结果保存到该字段中,然后您用第二个 new Stage() 的结果覆盖它。现在您打开了 2 个新阶段,但 this.stage 仅引用第二个阶段。