KeyPressed event in java

Depending on where you want to trap the “enter” key, you could use an ActionListener (on such components such as text components or buttons) or attach a key binding to you component

public class MyPanel extends JPanel {

    public MyPanel() {

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

        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "onEnter");

        am.put("onEnter", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Enter pressed
            }
        });

    }

}

This will rely on the component being focused.

Leave a Comment