【问题标题】:JavaFx closing Stages unpredictable behaviourJavaFx 关闭阶段不可预知的行为
【发布时间】:2021-03-12 18:45:15
【问题描述】:

所以我有一个基于 Hydra 的程序。弹出一个窗口,当试图关闭它时,它会关闭,但会在其位置弹出两个窗口。有两种方法可以关闭窗口,按关闭按钮或红叉。

我的问题是程序的行为非常不可预测,有时它会关闭它并打开 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();
        }
    }

【问题讨论】:

    标签: java javafx


    【解决方案1】:

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

    【讨论】:

    • 感谢您通过删除实例变量并仅通过参数传递阶段。
    猜你喜欢
    • 2018-09-29
    • 2012-04-30
    • 2014-12-24
    • 2014-07-10
    • 2014-04-21
    • 2014-04-07
    • 1970-01-01
    • 2017-11-10
    相关资源
    最近更新 更多