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
也必须被覆盖/实施!
可能最好的解决方法是使用带有Document
的DocumentFilter
,它可以删除任何类型,粘贴或插入的空格。 我写了一篇关于一个小Swing程序的博客文章,该程序演示了这种技术(在这种情况下只允许整数输入) – 描述 源 。
可以扩展Document
的子类型,但更容易出错(并将您与特定实现联系起来)。
试图拦截按键实际上并不起作用(它处于错误的抽象级别,因此错过任何其他方式可以插入文本,如粘贴,dnd等)。
JFormattedTextField
是一种确保任何UI都耗费大量时间的好方法。
您可以使用键盘映射。 看看这个示例禁止空间将如下所示:
KeyStroke keyStroke = KeyStroke.getKeyStroke(Character.valueOf(' '), 0); textField.getInputMap(JComponent.WHEN_FOCUSED).put(keyStroke, "none");
- 在Java中访问内存的最佳方法是什么,类似于mmap?
- Java鼠标“手电筒”效果如何?
- 按Jms ID选择消息的语法
- org.springframework.web.util.NestedServletException:请求处理失败; 嵌套exception是REST with Spring中的java.lang.NullPointerException
- Java 8 DateTimeFormatter解析不同重要性的可选小数秒
- 如何在Java Swing中设置当前屏幕大小?
- 关于arraylist的链表的比较
- 带有NativePRNG和SHA1PRNG的SecureRandom
- 将JFrame插入Swing中的Tab