如果結果存在,則用戶按下確定。如果沒有結果存在,則可能是按下用戶的取消,但他們可能剛剛關閉使用操作系統關閉窗口功能的對話窗口。
Optional<String> result = new TextInputDialog().showAndWait();
if (result.isPresent()) {
// ok was pressed.
} else {
// cancel might have been pressed.
}
要真正知道,如果是按下按鈕,您可以使用過濾器作爲Dialog javadoc節「對話框驗證/攔截動作按鈕」指出。
final Button cancel = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
cancel.addEventFilter(ActionEvent.ACTION, event ->
System.out.println("Cancel was definitely pressed")
);
示例代碼:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import java.util.Optional;
public class DialogSample extends Application {
@Override
public void start(Stage stage) throws Exception {
Button showButton = new Button("show");
showButton.setOnAction(event -> showDialog(stage));
showButton.setPrefWidth(100);
stage.setScene(new Scene(showButton));
stage.show();
showButton.fire();
}
private void showDialog(Stage stage) {
TextInputDialog dialog = new TextInputDialog();
dialog.initOwner(stage);
dialog.setTitle("Delimiter");
dialog.setHeaderText("Enter the delimiter");
final Button ok = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK);
ok.addEventFilter(ActionEvent.ACTION, event ->
System.out.println("OK was definitely pressed")
);
final Button cancel = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
cancel.addEventFilter(ActionEvent.ACTION, event ->
System.out.println("Cancel was definitely pressed")
);
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
System.out.println("Result present => OK was pressed");
System.out.println("Result: " + result.get());
} else {
System.out.println("Result not present => Cancel might have been pressed");
}
}
public static void main(String[] args) {
Application.launch();
}
}
的Javadoc並不清楚這一點。考慮到文件的問題:http://bugs.java.com – Puce