【问题标题】:Close an existing alert without button in runLater在 runLater 中关闭没有按钮的现有警报
【发布时间】:2018-03-19 10:35:27
【问题描述】:

我希望我的应用程序打开一个用户无法关闭的对话框,但是当他的手机重新连接时它会关闭(他对打开的对话框有耐心)

我目前正在使用 Platform.runlater 打开警报对话框,如下所示:

phoneConnected.getObservable().addListener(observable -> {
      LOG.info("identifyObs " + phoneConnected.getBooleanDataValue().getValue());
      if (phoneConnected.getBooleanDataValue() != null && !phoneConnected.getBooleanDataValue().getValue()) {
        Platform.runLater(() -> alert.show());
      }
      if (phoneConnected.getBooleanDataValue().getValue()) {
        System.out.println("ok");
        alert.close();
        Platform.runLater(() -> alert.close());
      }
    });

事实是,当 observable 变为“true”时,我在控制台中得到了“ok”,但对话框没有关闭..

我在 runLater 中尝试过,在 runLater 中尝试过,有什么想法吗?

我想说,我见过这个:Javafx: Close alert box (or, any dialog box) programatically 但它不起作用..

【问题讨论】:

    标签: javafx dialog javafx-8 observable


    【解决方案1】:

    如果未设置结果且没有可用的按钮,Alert 似乎无法正确关闭。您可以通过分配任意ButtonType 作为结果来解决此问题:

    Alert alert = new Alert(Alert.AlertType.NONE, "wait for it");
    
    // set result to allow programmatic closing of alert
    alert.setResult(ButtonType.OK);
    
    Button btn = new Button("Start");
    btn.setOnAction(evt -> {
        btn.setDisable(true);
    
        // make alert appear / disappear
        Thread t = new Thread(() -> {
            boolean showing = false;
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(NewFXMain2.class.getName()).log(Level.SEVERE, null, ex);
                }
                Runnable action = showing ? alert::close : alert::show;
                Platform.runLater(action);
                showing = !showing;
            }
        });
        t.setDaemon(true);
        t.start();
    });
    

    【讨论】:

    • 是的!就是这样,我只需要“alert.setResult(ButtonType.OK);”在我的代码中,它现在就像一个魅力!
    • hmm ... 听起来像一个错误 (?) - 或者我们可以想象任何需要/需要这种行为的用例吗?
    • 好的,我想我理解了逻辑:a)程序关闭与通过窗口按钮关闭处于相同的“异常”类别b)dialog.close的api文档指定了允许异常关闭时的规则关。即 i) 仅具有一个按钮或 ii) 具有多个按钮,其中一个是 cancel_close。 AlertType.NONE 没有按钮,因此它遇到了(未指定?在 fxDialog.permissionToClose 的实现中看到的)特殊情况,即结果必须为 != null。你找到了一个完美的角落案例:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2014-01-19
    • 1970-01-01
    相关资源
    最近更新 更多