How can I forbid users to put blanks into a JTextField?
It should not even be possible to write blanks.
views:
344answers:
4You can use a keymap. Check out this example disallowing space would be look like this:
KeyStroke keyStroke = KeyStroke.getKeyStroke(Character.valueOf(' '), 0);
textField.getInputMap(JComponent.WHEN_FOCUSED).put(keyStroke, "none");
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);
}
};
textField = new JTextField(doc);
Probably the best way to go about this is to use a Document
with a DocumentFilter
that removes any typed, pasted or otherwise inserted spaces. I wrote a weblog entry about a small Swing program that demonstrates this techique (in that case to allow only interger input) - Description Source.
Extending an subtype of Document
is possible, but is more error-prone (and ties you to a particular implementation).
Trying to intercept key presses doesn't actually work (it's at the wrong level of abstraction, so misses out any other way you could insert text such as pasting, dnd, etc.).
JFormattedTextField
is a good way to make sure any UI sucks big time.