【问题标题】:How to setText from a CompletableFuture如何从 CompletableFuture 中设置文本
【发布时间】:2019-09-25 12:02:47
【问题描述】:

我在通过 completableFuture 设置窗口名称时遇到问题。 我需要获取用户所在的帐户,并以此命名主窗口。

MainWindow mainWindow = this;
...
CompletableFuture.supplyAsync(() -> {
        while(true) {
            try {
                // wait until the account is chosen
                if (MainWindow.idAccount > 0 ) {
                    ResultSet rs = // some request to the db
                    rs.next();
                    return rs.getString(1);
                }
            } catch (Exception e) {
                System.out.println("Error while getting the address of the account. " + e.getMessage());
            }
        }
    }).thenAccept(account -> {
        System.out.println(account);
        mainWindow.setText("POS - " + account);
    });

一切正常,实际上在 .thenAccept() 中,控制台打印出正确的帐户地址。但是,文本永远不会设置。

可能是关于线程之间的访问吗?提前致谢。

【问题讨论】:

  • 您的 supplyAsync 阶段正在公共 fork-join 池中执行,但更新 UI 必须发生在 UI 线程上(例如 Event Dispatch Thread (EDT ) 在 Swing 中)。您应该使用thenAcceptAsync 变体在 UI 线程上安排舞台——请参阅my other comment

标签: java completable-future


【解决方案1】:

我假设 MainWindow 是一个 Swing 组件。 Swing 组件在 EDT 中更新。

SwingUtilities.invokeLater(() -> mainWindow.setText("POS - " + account));

附注:如果是框架,您可以尝试使用setTitle 设置标题。

【讨论】:

  • 在这种情况下可以使用thenAcceptAsync(/*Consumer*/, SwingUtilities::invokeLater)
  • 这一切都假设 OP 使用的是 AWT 或 Swing,这在任何地方都没有说过。例如,JavaFX 的解决方案看起来会有所不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多