问题
What could be the problem with the snippet below?
@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);
}
Thanks in advance for the help.
回答1:
By using Thread.sleep
on the application thread you prevent the UI from updating. To prevent this you need to run the code for waiting/shutting down on a different thread and allow the application thread to continue doing it's job:
@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();
}
You may want to consider using Platform.exit() instead of System.exit
though.
回答2:
Seems like you are on the UI Thread, therefore the text is not updating as you are on the same thread as the rest of your code.
You should to use Platform.runLater :
FutureTask<Void> updateUITask = new FutureTask(() -> {
lblStatus.setText("Logging out..");
}
Platform.runLater(updateUITask );
回答3:
This below is what worked for me:
@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);
}
});
}
来源:https://stackoverflow.com/questions/48702200/javafx-code-before-thread-sleep1000-doesnt-work-why