JTextField中没有空格 [英] No blanks in JTextField
本文介绍了JTextField中没有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何禁止用户将空格放入JTextField?
甚至不可能写空格。
How can I forbid users to put blanks into a JTextField?
It should not even be possible to write blanks.
推荐答案
我建议使用扩展的PlainDocument设置JTextField的Document,在其中覆盖insertString方法。 (也很好限制大小...)
类似于:
I would suggest to set the Document of the JTextField with an extended PlainDocument in which you override the insertString method. (Also nice to limit the size...)
Something like:
Document doc = new PlainDocument() {
@Override
public void insertString(int offs, String str, AttributeSet attr)
throws BadLocationException {
String newstr = str.replaceAll(" ", ""); // could use "\\s" instead of " "
super.insertString(offs, newstr, attr);
}
@Override
public void replace(int offs, int len, String str, AttributeSet attr)
throws BadLocationException {
String newstr = str.replaceAll(" ", ""); // could use "\\s" instead of " "
super.replace(offs, len, newstr, attr);
}
};
textField.setDocument(doc);
编辑:
替换
也必须被覆盖/实施!
replace
must also be overrided/implemented!
这篇关于JTextField中没有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文