[英]JavaFx custom alert stage
我正在嘗試創建一個自定義警報,該警報將向用戶顯示一條消息,直到完成任務(doOperation()),然后關閉自定義警報並繼續該過程。 但是它不能正常工作。 它阻塞了Fx線程,但沒有在屏幕上顯示該階段,然后立即關閉。 我在下面的代碼中缺少什么?
class MyClass{
void doOperation(){
//fetch data from DB. Nothing fancy. Simply getting data from jdbc and processes the data which may take a few secs.
}
void fetchProcessData(){
Stage customStage = new Stage();
GridPane stageGrid = new GridPane();
stageGrid.setAlignment(Pos.CENTER);
stageGrid.setHgap(10);
stageGrid.setVgap(10);
Label contextLabel = new Label("Wait...");
stageGrid.add(contextLabel, 0, 1);
Scene scene = new Scene(stageGrid, 300, 150);
customStage.setScene(scene);
customStage.setTitle(title);
customStage.initStyle(stageStyle);
customStage.initModality(modality);
customStage.show();
try {
doOperation();
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
customStage.close();
}
}
您需要在后台線程上執行長時間運行的操作,並在操作完成后進行更新。
最簡單的方法是為此使用Platform.runLater
:
customStage.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
doOperation();
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close stage on javafx application thread
Platform.runLater(new Runnable() {
@Override
public void run() {
customStage.close();
}
});
}
}).start();
Task
類提供了一些功能,可以在javafx應用程序線程上進行中間更新,並允許您注冊在該線程上處理不同結果的處理程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.