While @camickr has a nice, simple solution that I have, a complex but more complete option is to work with the Document associated with JTextArea and override its insertString() . Sometimes you already do this, for example, to prevent letters from being added to the number field. The advantage is that KeyBinding is that it will also be caught when the user copies and pastes into JTextArea. So, if the user copies and pastes the "foo bar" into the area, KeyBinding will not catch this (I'm sure I'm wrong here?) And the document technique. For example, very schematically:
@Override public void insertString(int offset, String str, AttributeSet a) throws BadLocationException { if (str.contains(" ")) callMySpecialSpaceMethod(); super.insertString(offset, str, a); }
As @camickr pointed out, instead of directly subclassing and overriding Document.insertString (), you can set DocumentFilter instead. ( approve composition over inheritance .) Unfortunately, this is a bit inconvenient with casting, but here is the basic code:
((AbstractDocument)myTextArea.getDocument()).setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String str, AttributeSet a) throws BadLocationException { if (str.contains(" ")) callMySpecialSpaceMethod(); fb.insertString(offset, str, a); } });
This is a lot more work with KeyBinding, so if you really don't need to be so thorough, or you already do it for another reason, KeyBinding is easier. And it depends on your requirements - in your case, I donβt think you care if they copy and paste.
source share