如果JFormattedTextField使用AbstractFormatter进行转换,还是使用DocumentFilter来拒绝任何不是有效百分比值的内容?
这是一个示例DocumentFilter(未经过测试,阅读文档):
class PercentageFilter extends DocumentFilter {
insertString(FilterBypass bp, int offset, String adding, AttributeSet attrs) {
Document doc = bp.getDocument();
String text = doc.getText(0, offset) + adding + doc.getText(offset, doc.getLength()-offset);
try {
double d = Double.parseDouble(text);
if(d < 0 || 100 < d) {
// to big or too small number
return;
}
}
catch(NumberFormatException ex) {
// invalid number, do nothing.
return;
}
// if we come to this point, the entered number
// is a valid value => really insert it into the document.
bp.insertString(offset, adding, attrs);
}
}
Run Code Online (Sandbox Code Playgroud)
你想要覆盖remove()和replace类似.
(我想可能会有更高效的实现,但我认为这对于大多数用户的打字速度来说足够快.)
此过滤器将从您的AbstractFormatter实现的getDocumentFilter方法返回.
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |