我在通过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
设置标题。