How to call a method after pressing space in JTextArea

Sorry for the most likely simple question, but how can I call a method every time a whitespace is pressed in JTextArea? I tried connecting a keylistener to the text area, but I was not able to get this to work. Thanks.

+4
source share
3 answers

Read the Swing tutorial on How to Use Key Bindings .

The tutorial provides examples, and you can find many other examples on the forum.

When creating the custom action you want to perform, you must extend the TextAction.

+6
source
JTextArea jt=new JTextArea(); jt.addKeyListener(new KeyListener(){ public void keyPressed(KeyEvent ke){ if(ae.getKeyCode()==KeyEvent.VK_SPACE){ //call your method } } }); 
+4
source

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.

0
source

All Articles