簡體   English   中英

如何在JavaFX的TextInputDialog中執行輸入檢查?

[英]How to perform input checks in TextInputDialog in JavaFX?

我有下面的代碼。 它描述了一個簡單的TextInputDialog (包含一個文本字段和OK按鈕)。 如何執行輸入檢查? (例如,驗證輸入是數字/非空等等)。 在底端, 我希望如果輸入錯誤,則禁用“確定”按鈕,或者如果我按“確定”,那么如果輸入錯誤,則什么也不會發生。

TextInputDialog tid = new TextInputDialog("250");
tid.setTitle("Text Input Dialog");
tid.setHeaderText("Input check example");
tid.setContentText("Please enter a number below 100:");
Optional<String> result = tid.showAndWait();
result.ifPresent(name -> System.out.println("Your name: " + name));

在“ ifPresent”部分中,我可以檢查輸入,但這將在對話框關閉后進行。 我該如何解決?

這是對話框

您可以在TextInputDialog上使用getEditor()獲取基礎TextField並在對話框的DialogPane上使用DialogPane lookupButton(ButtonType)以獲得OK- Button 然后,您可以使用綁定來實現所需的行為:

Button okButton = (Button) tid.getDialogPane().lookupButton(ButtonType.OK);
TextField inputField = tid.getEditor();
BooleanBinding isInvalid = Bindings.createBooleanBinding(() -> isInvalid(inputField.getText()), inputField.textProperty());
okButton.disableProperty().bind(isInvalid);

現在,您可以創建一個方法isInvalid()來驗證您的輸入,並返回true (如果應該禁用按鈕)或false (如果應該啟用)。

當然,可以通過在綁定上使用not()方法來扭轉這種邏輯並創建一個isValid方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM