如何在JavaFX的TextInputDialog中实现输入校验?
嘿,这问题我熟!给TextInputDialog加输入校验其实很简单,咱们分几种常见场景一步步来,直接上可运行的代码和实用解释:
核心思路
首先得知道:TextInputDialog自带的输入框可以通过getEditor()获取,确认按钮则可以通过getDialogPane().lookupButton(ButtonType.OK)拿到。我们的核心就是实时监听输入变化或者拦截按钮点击事件,来校验输入合法性,进而控制按钮状态或阻止非法提交。
1. 非空校验(输入为空/纯空格时禁用确认按钮)
这种方式最直观,用户输入不合法时直接让确认按钮点不动,从根源上避免无效提交:
import javafx.application.Application; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.TextInputDialog; import javafx.scene.control.TextField; import javafx.stage.Stage; import java.util.Optional; public class InputDialogDemo extends Application { @Override public void start(Stage stage) { TextInputDialog tid = new TextInputDialog("250"); tid.setTitle("Text Input Dialog"); tid.setHeaderText("Input check example"); tid.setContentText("Please enter content:"); // 获取对话框的输入框 TextField editor = tid.getEditor(); // 获取确认按钮 Button okButton = (Button) tid.getDialogPane().lookupButton(ButtonType.OK); // 非空校验:输入为空或纯空格时禁用按钮 editor.textProperty().addListener((observable, oldValue, newValue) -> { boolean isInvalid = newValue.trim().isEmpty(); okButton.setDisable(isInvalid); }); // 显示对话框并处理合法输入 Optional<String> result = tid.showAndWait(); result.ifPresent(input -> System.out.println("You entered: " + input)); } public static void main(String[] args) { launch(args); } }
解释:通过监听输入框的文本变化,实时判断是否为空(用trim()避免纯空格的情况),然后设置按钮的disable属性。用户输入合法前,确认按钮一直是灰色不可点击状态。
2. 数字校验(仅允许输入数字,非法时禁用按钮)
如果要求输入必须是数字(整数/小数),我们可以结合正则校验和输入拦截,既实时禁用按钮,还能阻止用户输入非法字符:
import javafx.application.Application; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.TextInputDialog; import javafx.scene.control.TextField; import javafx.stage.Stage; import java.util.Optional; public class NumberInputDialogDemo extends Application { @Override public void start(Stage stage) { TextInputDialog tid = new TextInputDialog("250"); tid.setTitle("Text Input Dialog"); tid.setHeaderText("Input check example"); tid.setContentText("Please enter a number:"); TextField editor = tid.getEditor(); Button okButton = (Button) tid.getDialogPane().lookupButton(ButtonType.OK); // 实时数字校验:输入非法时禁用按钮 editor.textProperty().addListener((observable, oldValue, newValue) -> { // 正则匹配整数或小数,允许空(如果要求必须输入数字,就去掉|| newValue.isEmpty()) boolean isValid = newValue.matches("^\\d+(\\.\\d+)?$") || newValue.isEmpty(); okButton.setDisable(!isValid); }); // 额外:拦截非法输入,用户连非数字字符都打不进去 editor.setOnKeyTyped(event -> { char inputChar = event.getCharacter().charAt(0); // 允许数字、小数点(且只能有一个) if (!Character.isDigit(inputChar) && inputChar != '.' || (inputChar == '.' && editor.getText().contains("."))) { event.consume(); // 吃掉事件,不允许输入 } }); Optional<String> result = tid.showAndWait(); result.ifPresent(input -> System.out.println("You entered number: " + input)); } public static void main(String[] args) { launch(args); } }
解释:
- 正则表达式
^\\d+(\\.\\d+)?$匹配整数或小数,如果只需要整数,改成^\\d+$即可。 setOnKeyTyped监听按键输入,直接阻止非数字和重复小数点的输入,提升用户体验。
3. 点击确认后校验(不实时禁用按钮,非法时提示)
如果不想实时禁用按钮,而是等用户点击确认后再校验并提示错误,可以给按钮加事件过滤器:
import javafx.application.Application; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.TextInputDialog; import javafx.stage.Stage; import javafx.event.ActionEvent; import java.util.Optional; public class PostClickCheckDemo extends Application { @Override public void start(Stage stage) { TextInputDialog tid = new TextInputDialog("250"); tid.setTitle("Text Input Dialog"); tid.setHeaderText("Input check example"); tid.setContentText("Please enter a non-empty number:"); Button okButton = (Button) tid.getDialogPane().lookupButton(ButtonType.OK); // 点击确认时触发校验 okButton.addEventFilter(ActionEvent.ACTION, event -> { String input = tid.getEditor().getText().trim(); // 非空校验 if (input.isEmpty()) { showErrorAlert("Input cannot be empty!"); event.consume(); // 阻止对话框关闭 return; } // 数字校验 if (!input.matches("^\\d+(\\.\\d+)?$")) { showErrorAlert("Please enter a valid number!"); event.consume(); // 阻止对话框关闭 } }); Optional<String> result = tid.showAndWait(); result.ifPresent(input -> System.out.println("Valid input: " + input)); } // 封装错误提示方法 private void showErrorAlert(String message) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Input Error"); alert.setContentText(message); alert.showAndWait(); } public static void main(String[] args) { launch(args); } }
解释:点击确认按钮后,先校验输入合法性,如果非法就弹出错误提示框,并用event.consume()阻止对话框关闭,用户修正输入后才能重新提交。
内容的提问来源于stack exchange,提问作者HadarShab
相关产品推荐
相关产品推荐

