1

So I have a Submit button with an ActionEvent that consists of around 50 lines of code. How would I assign the exact same ActionEvent for the JFrame as the Submit button whenever it detects the Enter key being pressed? This is what my Submit button's ActionEvent looks like

        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?

btrballin
  • 1,420
  • 3
  • 25
  • 41
  • http://stackoverflow.com/questions/5344823/how-can-i-listen-for-key-presses-within-java-swing-across-all-components – jheimbouch Feb 09 '16 at 03:24

3 Answers3

3

Start by taking a look at How to Use Root Panes and in particular 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

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

Have a look at How to Use Key Bindings and How to Use Actions for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

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);
shmosel
  • 49,289
  • 6
  • 73
  • 138
0

One way to do this is to use the .doClick() method on the Submit button and create a 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);
btrballin
  • 1,420
  • 3
  • 25
  • 41
  • So, unless the component which the `KeyListener` is registered to has focus, a `KeyListener` won't work. As a general rule of thumb, you should avoid using `KeyListener` with text components. There are also simpler and easier ways to achieve the same result (rather than having to register a `KeyListener` to dozens of components) – MadProgrammer Feb 09 '16 at 05:28