KeyPressed event in java

2020-03-03 09:21发布

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
}

3条回答
乱世女痞
2楼-- · 2020-03-03 09:23

One way is to implement the KeyListener interface and its key event methods. For example,

public class MyClass  implements KeyListener {
    public void keyTyped(KeyEvent e) {
        // Invoked when a key has been typed.
    }

    public void keyPressed(KeyEvent e) {
        // Invoked when a key has been pressed.
        if (e.getKeyCode() == KeyEvent.VK_ENTER && yourOtherCondition) {
            myMethod();
        }
    }

    public void keyReleased(KeyEvent e) {
        // Invoked when a key has been released.
    }
}

Then add this listener with

myComponent.addKeyListener(new MyClass());

Or if you prefer,

myComponent.addKeyListener(new KeyListener() {
    public void keyPressed(KeyEvent e) { /* ... */ }

    public void keyReleased(KeyEvent e) { /* ... */ }

    public void keyTyped(KeyEvent e) { /* ... */ }
});

See this for more details.

查看更多
再贱就再见
3楼-- · 2020-03-03 09:26

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.

查看更多
▲ chillily
4楼-- · 2020-03-03 09:40

Caveat - It's been a while since I did desktop applications, but the java.awt.Component class has an addKeyListener() method which you can use to register a class that implements KeyListener - is this what you are looking for?

查看更多
登录 后发表回答