【问题标题】:Is there any way in javafx or fxml to validate TextField character's length?javafx 或 fxml 中有什么方法可以验证 TextField 字符的长度吗?
【发布时间】:2020-07-06 11:42:56
【问题描述】:

文本字段不接受除数字 [0-9] 以外的任何字符及其长度,在我的情况下它是 11,但在正则表达式中添加 {11} 后,文本字段不接受任何内容。请帮忙!

代码在这里:

public class NumberField extends JFXTextField {

        @Override
        public void replaceText(int i, int i1, String string){

            if (string.matches("[0-9]{11}") || string.isEmpty()) //{11} is length of number
                super.replaceText(i , i1 , string);

        }

【问题讨论】:

  • 抱歉校对。文本字段不接受除数字 [0-9] 以外的任何字符并采用特定长度输入,在我的情况下为 11,但在正则表达式“the”文本字段中添加 {11}不接受任何事情。请帮忙!

标签: java regex swing jtextfield number-formatting


【解决方案1】:
public class ContactField extends JFXTextField {

    /*
     *
     * i is current length / value
     * i1 is previous length / value
     * string is value / char i-e currently keytyped
     *
     * Here:
     *
     * string.matches[0-9], it matches single current key typed value to the regex expression(one at a time)
     * string.empty() is used for backspace key
     */
    @Override
    public void replaceText(int i, int i1, String string) {
         if ((string.matches("[0-9]") || string.isEmpty()) && i <= 10) //for validating numbers length start from 0;
             super.replaceText(i, i1, string);
         }

    /*
     * It maintains prev and current values when selected char( by arrows keys like from middle) is deleted;
     *
     */
    @Override
    public void replaceSelection(String replacement) {
        super.replaceSelection(replacement);
    }
}

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 2021-10-03
    • 2021-07-20
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多