JavaFX 自定义 TextField 限制

JavaFX custom TextField restriction

我正在为我的数学老师申请将平面从矢量方程形式转换为标量方程形式。

对于我的输入 TextField,我有这段代码。

TextField input = new TextField();
input.setPromptText(" (x,y,z) + q(a,b,c) + p(a,b,c) ");

我想将输入限制为给定格式(通常限制输入格式)。

我能想到的唯一方法是让线程或动作侦听器不断调用

input.getText();

然后比较字符串的每个索引,看它是否是正确的输入类型(是数字,还是括号...等)。

这似乎是一种非常 "noobish" 的方法...有谁知道更好的方法吗?也许 java 有一些内置的方法?

查看第 3 方 Controls FX 库,它在正则表达式上具有 validation/decoration of input controls and for which you can createRegExValidator. Use regex101 to fashion your regex. Once validation passes, you can use pattern matching 功能,可以从输入字符串中检索输入值。

由于这主要是给你做一个学习练习,所以我暂时不会提供代码。

You can use controls FX validation support to make this work :

在您的控制器中,您可以将验证器设置为您的文本字段:

validationSupport = new ValidationSupport();
        validationSupport.registerValidator(textField, true, ValidationForm.formatValidate);

然后您可以根据需要在单独的 class:

中设计您的验证器
public class ValidationForm {

    /**
     * Field allows only if correctly formatted
     */
    public static Validator<String> formatValidate = (Control control, String value) -> {
        boolean condition = value != null
                ? !value.matches("^\({1}+[0-9]+\,[0-9]+\,[0-9]+\){1}+\+{1}"
                        + "+[a-z]{1}+\({1}+[0-9]+\,[0-9]+\,[0-9]+\){1}+\+{1}"
                        + "+[a-z]{1}+\({1}+[0-9]+\,[0-9]+\,[0-9]+\){1}$") : value == null;

        return ValidationResult.fromMessageIf(control, "Not a valid input \n"
                + "Should be formatted \" (x,y,z) + q(a,b,c) + p(a,b,c) \"",
               Severity.ERROR, condition);
    };
   ...