【发布时间】:2013-10-06 18:00:31
【问题描述】:
假设用户必须在 Jtextfield 中输入一个 Double 值,然后进行计算。
但是如果用户突然使用超过 1 个句点,它会触发 NumberFormatException,所以我假设解决方案是使用文档过滤器来过滤掉任何额外的句点或捕获异常并通知用户输入无效
目前使用 DocumentFilter 只允许数字和句点,但我的问题是如何过滤掉第二个句点
PlainDocument filter = new PlainDocument();
filter.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException
{
fb.insertString(off, str.replaceAll("[^0-9.]", ""), attr);
}
@Override
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
throws BadLocationException
{
fb.replace(off, len, str.replaceAll("[^0-9.]", ""), attr);
}
});
apm.setDocument(filter);
例子
无效 输入:1.2.2
有效 输入:1.22
【问题讨论】:
标签: java swing jtextfield documentfilter