如何在 Java(JTextField 类)中实现只允许输入数字? [英] How to implement in Java ( JTextField class ) to allow entering only digits?
本文介绍了如何在 Java(JTextField 类)中实现只允许输入数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Java(JTextField
类)中实现只允许输入数字?
How to implement in Java ( JTextField
class ) to allow entering only digits?
推荐答案
向 JTextField 中使用的 (Plain)Document 添加 DocumentFilter 以避免非数字.
Add a DocumentFilter to the (Plain)Document used in the JTextField to avoid non-digits.
PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException
{
fb.insertString(off, str.replaceAll("\D++", ""), attr); // remove non-digits
}
@Override
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
throws BadLocationException
{
fb.replace(off, len, str.replaceAll("\D++", ""), attr); // remove non-digits
}
});
JTextField field = new JTextField();
field.setDocument(doc);
这篇关于如何在 Java(JTextField 类)中实现只允许输入数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文