4
我想創建一個javafx輸入對話框,我把它放在一個任務中,但是我的代碼沒有創建任何對話框。在JavaFX任務中創建一個JavaFX對話框
Task<Void> passwordBox = new Task<Void>() {
@Override
protected Void call() throws Exception {
TextInputDialog dialog = new TextInputDialog("walter");
dialog.setTitle("Text Input Dialog");
dialog.setHeaderText("Look, a Text Input Dialog");
dialog.setContentText("Please enter your name:");
// Traditional way to get the response value.
Optional<String> result = dialog.showAndWait();
if (result.isPresent()){
System.out.println("Your name: " + result.get());
}
// The Java 8 way to get the response value (with lambda expression).
result.ifPresent(name -> System.out.println("Your name: " + name));
return null;
}
};
Thread pt = new Thread(passwordBox);
pt.start();
調試,它是Task類
catch (final Throwable th) {
// Be sure to set the state after setting the cause of failure
// so that developers handling the state change events have a
// throwable to inspect when they get the FAILED state. Note
// that the other way around is not important -- when a developer
// observes the causeOfFailure is set to a non-null value, even
// though the state has not yet been updated, he can infer that
// it will be FAILED because it can be nothing other than FAILED
// in that circumstance.
task.runLater(() -> {
task._setException(th);
task.setState(State.FAILED);
});
// Some error occurred during the call (it might be
// an exception (either runtime or checked), or it might
// be an error. In any case, we capture the throwable,
// record it as the causeOfFailure, and then rethrow. However
// since the Callable interface requires that we throw an
// Exception (not Throwable), we have to wrap the exception
// if it is not already one.
if (th instanceof Exception) {
throw (Exception) th;
} else {
throw new Exception(th);
}
如果我不把它導致應用程序掛起裏面的任務對話框的下面捕獲方法中去。
你知道,'showAndWait'不會阻止JavaFX應用程序線程,因此並不需要在不同的線程上運行(其實**不應該在非fx應用程序不同的線程上運行**)? – fabian
我不確定你爲什麼這樣做。您提供的示例任務除了顯示對話框外沒有其他任何操作,可以在沒有任務的情況下在JavaFX應用程序線程上完成。所以我真的不知道你在做什麼,也許你正在試圖做到這一點:[JavaFX2:我可以暫停後臺任務/服務?](http://stackoverflow.com/questions/14941084/javafx2- can-i-pause-a-background-task-service) – jewelsea
是的,我需要保持主線程以獲取來自用戶的輸入,我嘗試使用鏈接中提供的未來任務概念,但它會停止應用程序並使反應遲鈍。 – bhavesh