You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX实现TextField仅允许输入Double双精度数值的方法求教

方案一:自定义DoubleTextField(推荐)

该方案和你现有整数输入控件的实现逻辑对齐,不会出现文本监听方案可能引发的属性递归更新异常,适配你要求的双精度数值输入规则:

import java.util.regex.Pattern;
import javafx.scene.control.TextField;

public class DoubleTextField extends TextField {
    // 正则说明:支持空值(允许清空)、纯整数、带1-2位小数的数值,支持输入小数点后的中间状态
    private static Pattern doublePattern = Pattern.compile("^\\d*(\\.\\d{0,2})?$");

    @Override
    public void replaceText(int start, int end, String text) {
        // 先拼接出替换后的完整文本再校验
        String newText = getText().substring(0, start) + text + getText().substring(end);
        if (validate(newText)) {
            super.replaceText(start, end, text);
        }
    }

    @Override
    public void replaceSelection(String text) {
        int start = getSelection().getStart();
        int end = getSelection().getEnd();
        String newText = getText().substring(0, start) + text + getText().substring(end);
        if (validate(newText)) {
            super.replaceSelection(text);
        }
    }

    private boolean validate(String text) {
        return doublePattern.matcher(text).matches();
    }
}

使用时直接替换原有TextField为DoubleTextField即可,默认支持:

  • 完全清空输入框
  • 输入纯整数、1-2位小数的双精度数
  • 支持输入小数点后的临时中间状态(如输入12.时不会被拦截,可继续输入小数位)
  • 如果需要支持负数,可将正则修改为^-?\\d*(\\.\\d{0,2})?$;如果需要调整小数位数,将{0,2}改为对应位数上限即可。
方案二:文本监听器实现

如果不想自定义控件,可使用优化后的监听方案,解决原有清空异常问题:

myTxtField.textProperty().addListener((observable, oldValue, newValue) -> {
    if (!newValue.matches("^\\d*(\\.\\d{0,2})?$")) {
        myTxtField.setText(oldValue);
    }
});

如果绑定了textProperty的其他监听,建议在setText前临时移除当前监听避免重复触发,优化后写法:

ChangeListener<String> doubleListener = (observable, oldValue, newValue) -> {
    if (!newValue.matches("^\\d*(\\.\\d{0,2})?$")) {
        myTxtField.textProperty().removeListener(doubleListener);
        myTxtField.setText(oldValue);
        myTxtField.textProperty().addListener(doubleListener);
    }
};
myTxtField.textProperty().addListener(doubleListener);

内容的提问来源于stack exchange,提问作者siggi_n

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:36:03