【发布时间】:2015-05-11 12:22:17
【问题描述】:
我在网上找遍了所有我尝试过的东西都没有奏效......
我发现我可以使用一些 JTextFormatterField 但它不起作用。
然后我发现我可以将 DocumentFilter 与正则表达式一起使用,而我做了什么:
JTextField jFormattedTextFieldMoneyToConvert = new JTextField();
((AbstractDocument) jFormattedTextFieldMoneyToConvert.getDocument()).setDocumentFilter(new DocumentFilter(){
Pattern regEx = Pattern.compile("^\\d+\\.?\\d*$");
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
Matcher matcher = regEx.matcher(text);
if (!matcher.matches()) {
return;
}
super.replace(fb, offset, length, text, attrs);
}
});
但它不起作用...它只接受数字。我希望它也接受点。而且我还需要它不要以点开头,也不要以点结尾。
我做错了什么?
【问题讨论】:
-
but it doesn't work...请定义... -
抱歉,我编辑了我的问题
-
I also need it to not to start with a dot and not to end with a dot.- 表达式为^\d+(\.\d+)?$,即至少一位数字可选地后跟一个点,并且至少再增加一位数字。
标签: java regex swing jtextfield documentfilter