KeyPressed event in java

CodeLover picture CodeLover · Oct 24, 2012 · Viewed 44.3k times · Source

I have just created a java tic-tac-toe game i would like to figure out how to run a method once the enter key is pressed during a certain condition an example is below...

if(/*condition is met*/){
     //keyListener
}

Answer

MadProgrammer picture MadProgrammer · Oct 24, 2012

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.