views:

344

answers:

4

How can I forbid users to put blanks into a JTextField?
It should not even be possible to write blanks.

+2  A: 

Try using a JFormattedTextField

kgiannakakis
A: 

You 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");
Tim Büthe
+2  A: 

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);
Carlos Heuberger
DocumentFilter is best. There are also methods to insert text other than insertString.
Tom Hawtin - tackline
@Tom: true, I've not seen that. A better way (I now know) for "filtering"!
Carlos Heuberger
+2  A: 

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.

Tom Hawtin - tackline