JavaFx - Thread.sleep(1000) 之前的代码不起作用,为什么?
JavaFx - Code before Thread.sleep(1000) doesn't work, why?
下面的代码片段可能有什么问题?
@FXML
private Button btnLogOut;
@FXML
private Label lblStatus;
@FXML
private void btnLogOut_Click() throws InterruptedException {
lblStatus.setText("Logging out.."); // Doesn't work..?
Thread.sleep(1000);
System.exit(0);
}
在此先感谢您的帮助。
您似乎在 UI 线程中,因此文本没有更新,因为您与其余代码在同一个线程中。
你应该使用 Platform.runLater :
FutureTask<Void> updateUITask = new FutureTask(() -> {
lblStatus.setText("Logging out..");
}
Platform.runLater(updateUITask );
以下是对我有用的:
@FXML
private Button btnLogOut;
@FXML
private Label lblStatus;
@FXML
private void btnLogOut_Click() throws InterruptedException {
lblStatus.setText("Logging out..");
Thread.sleep(100);
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(FXMLMainController.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(0);
}
});
}
通过在应用程序线程上使用 Thread.sleep
,可以防止 UI 更新。为防止这种情况,您需要 运行 将 waiting/shutting 的代码放在不同的线程上,并允许应用程序线程继续执行它的工作:
@FXML
private void btnLogOut_Click() {
// update ui
lblStatus.setText("Logging out..");
// delay & exit on other thread
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
System.exit(0);
}).start();
}
不过您可能要考虑使用 Platform.exit()
而不是 System.exit
。
下面的代码片段可能有什么问题?
@FXML
private Button btnLogOut;
@FXML
private Label lblStatus;
@FXML
private void btnLogOut_Click() throws InterruptedException {
lblStatus.setText("Logging out.."); // Doesn't work..?
Thread.sleep(1000);
System.exit(0);
}
在此先感谢您的帮助。
您似乎在 UI 线程中,因此文本没有更新,因为您与其余代码在同一个线程中。
你应该使用 Platform.runLater :
FutureTask<Void> updateUITask = new FutureTask(() -> {
lblStatus.setText("Logging out..");
}
Platform.runLater(updateUITask );
以下是对我有用的:
@FXML
private Button btnLogOut;
@FXML
private Label lblStatus;
@FXML
private void btnLogOut_Click() throws InterruptedException {
lblStatus.setText("Logging out..");
Thread.sleep(100);
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(FXMLMainController.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(0);
}
});
}
通过在应用程序线程上使用 Thread.sleep
,可以防止 UI 更新。为防止这种情况,您需要 运行 将 waiting/shutting 的代码放在不同的线程上,并允许应用程序线程继续执行它的工作:
@FXML
private void btnLogOut_Click() {
// update ui
lblStatus.setText("Logging out..");
// delay & exit on other thread
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
System.exit(0);
}).start();
}
不过您可能要考虑使用 Platform.exit()
而不是 System.exit
。