Я бы предложил установить Document для JTextField с расширенным PlainDocument, в котором вы переопределяете метод 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);
EDIT:
replace
также необходимо переопределить / внедрить!