JTextField中没有空格

我怎样才能禁止用户将空格放入JTextField?
甚至不可能写空白。

我建议使用扩展的PlainDocument设置JTextField的Document,在其中覆盖insertString方法。 (也很好限制大小……)
就像是:

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也必须被覆盖/实施!

可能最好的解决方法是使用带有DocumentDocumentFilter ,它可以删除任何类型,粘贴或插入的空格。 我写了一篇关于一个小Swing程序的博客文章,该程序演示了这种技术(在这种情况下只允许整数输入) – 描述 源 。

可以扩展Document的子类型,但更容易出错(并将您与特定实现联系起来)。

试图拦截按键实际上并不起作用(它处于错误的抽象级别,因此错过任何其他方式可以插入文本,如粘贴,dnd等)。

JFormattedTextField是一种确保任何UI都耗费大量时间的好方法。

您可以使用键盘映射。 看看这个示例禁止空间将如下所示:

 KeyStroke keyStroke = KeyStroke.getKeyStroke(Character.valueOf(' '), 0); textField.getInputMap(JComponent.WHEN_FOCUSED).put(keyStroke, "none");