简体   繁体   中英

How to call a method after the space bar is pressed in a JTextArea

Sorry for what is likely a simple question, but how can I call a method every time the space bar is pressed in a JTextArea? I have tried attaching a keylistener to the text area, but I wasn't able to get that to work. Thanks.

Read the Swing tutorial on How to Use Key Bindings .

The tutorial has examples and you can find plenty of other examples in the forum.

When you create the custom Action that you want to execute you would extend TextAction.

JTextArea jt=new JTextArea();

jt.addKeyListener(new KeyListener(){ 

    public void keyPressed(KeyEvent ke){ 

         if(ae.getKeyCode()==KeyEvent.VK_SPACE){
              //call your method
         }
    }
});

While @camickr has a good, simple solution which I have upvoted, a complex but more thorough option is to work with the Document associated with the JTextArea , and override it's insertString() method. Sometimes you are already doing this, for example, to prevent letters from getting added to a numeric field. The advantage is has over a KeyBinding is that it will also catch when the user copies and pastes into the JTextArea. So, if the user copies and pastes "foo bar" into the area, a KeyBinding will not catch that (I'm pretty sure, am I wrong here?) and the Document technique will. eg, very schematically:

@Override
public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
  if (str.contains(" "))
    callMySpecialSpaceMethod();
  super.insertString(offset, str, a);
}

As pointed out by @camickr, instead of directly subclassing and overriding Document.insertString(), one can set it's DocumentFilter instead. ( favor Composition over Inheritance .) Unfortunately, it's a bit clunky with some casting, but here's 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 that a KeyBinding so, unless you really need to be this thorough, or you are already doing this for another reason, the KeyBinding is simpler. And it depends on your requirements - in your case, I don't think you care if they copy and paste.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM