简体   繁体   English

如何使Enter键和Submit按钮具有相同的ActionEvent?

[英]How to make Enter key and Submit button have same ActionEvent?

So I have a Submit button with an ActionEvent that consists of around 50 lines of code. 所以我有一个带有ActionEvent的Submit按钮,该按钮包含大约50行代码。 How would I assign the exact same ActionEvent for the JFrame as the Submit button whenever it detects the Enter key being pressed? 当检测到按下Enter键时,如何为JFrame指定与提交按钮完全相同的ActionEvent This is what my Submit button's ActionEvent looks like 这就是我的提交按钮的ActionEvent样子

        btnSubmit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
             // miscellaneous code that needs to be repeated for 'Enter' key press
           }
        });

What and where would the code for giving the JFrame the same ActionEvent as the Submit button go? 用于为JFrame提供与Submit按钮相同的ActionEvent的代码是什么以及在哪里?

Start by taking a look at How to Use Root Panes and in particular JRootPane#setDefaultButton 首先看一下如何使用根窗格 ,特别是JRootPane#setDefaultButton

When you have components which may consume the Enter key (like text fields), you might need to consider using the key bindings API 如果您有可能使用Enter键的组件(如文本字段),则可能需要考虑使用键绑定API

InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter.pressed");
am.put("Enter.pressed", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        btnSubmit.doClick();
    }
});

Now, about now, I might consider making an Action which be applied to both the JButton and key binding 现在,我现在可以考虑制作一个适用于JButton和键绑定的Action

Have a look at How to Use Key Bindings and How to Use Actions for more details 有关更多详细信息,请参阅如何使用键绑定如何使用操作

I don't know if there's a more correct swing way, but this should do the trick: 我不知道是否有更正确的摆动方式,但这应该可以解决问题:

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        //...
    }
}
btnSubmit.addActionListener(listener);
btnEnter.addActionListener(listener);

One way to do this is to use the .doClick() method on the Submit button and create a KeyAdapter : 一种方法是在Submit按钮上使用.doClick()方法并创建KeyAdapter

    KeyAdapter Enter = new KeyAdapter(){
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                btnSubmit.doClick();
            }
        }
    };
    txtField1.addKeyListener(Enter);
    txtField2.addKeyListener(Enter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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