java 如何在 JTextArea 中按下空格键后调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15628617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:18:56  来源:igfitidea点击:

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

javaswingjtextarea

提问by nuclearPigi

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.

抱歉,这可能是一个简单的问题,但是每次在 JTextArea 中按下空格键时我如何调用方法?我曾尝试将密钥侦听器附加到文本区域,但无法使其正常工作。谢谢。

回答by camickr

Read the Swing tutorial on How to Use Key Bindings.

阅读有关如何使用键绑定的 Swing 教程。

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.

当您创建要执行的自定义操作时,您将扩展 TextAction。

回答by Arun Kumar Mudraboyina

JTextArea jt=new JTextArea();

jt.addKeyListener(new KeyListener(){ 

    public void keyPressed(KeyEvent ke){ 

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

回答by user949300

While @camickr has a good, simple solution which I have upvoted, a complex but more thorough option is to work with the Documentassociated 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 pastesinto 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. e.g., very schematically:

虽然@camickr 有一个很好的、简单的解决方案,我已经赞成,但一个复杂但更彻底的选择是使用与Document关联的JTextArea,并覆盖它的insertString()方法。例如,有时您已经这样做了,以防止将字母添加到数字字段中。与 KeyBinding 相比,它的优势在于当用户复制并粘贴到 JTextArea时,它也会被捕获。因此,如果用户将“foo bar”复制并粘贴到该区域中,KeyBinding 将无法捕捉到(我很确定,我错了吗?)而 Document 技术将捕捉到。例如,非常示意:

@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:

正如@camickr 所指出的,不是直接子类化和覆盖 Document.insertString(),而是可以将其设置为 DocumentFilter。(更喜欢 Composition 而不是 Inheritance。)不幸的是,它的一些转换有点笨拙,但这里是基本代码:

((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.

与 KeyBinding 相比,这需要做更多的工作,除非您真的需要如此彻底,或者您已经出于其他原因这样做了,否则 KeyBinding 会更简单。这取决于您的要求 - 就您而言,我认为您不关心他们是否复制和粘贴。