我在通过 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() 中,控制台打印出帐户的正确地址。但文本从未设置。
会不会是线程间访问的问题?提前致谢。
最佳答案
我假设 MainWindow 是一个 Swing 组件。 Swing 组件在 EDT 中进行了更新。
SwingUtilities.invokeLater(() -> mainWindow.setText("POS - " + account));
旁注:如果是框架,您可以尝试使用 setTitle
设置标题。
关于java - 如何从 CompletableFuture 设置文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58097911/