KeyPressed event in java

后端 未结 3 1769
南笙
南笙 2021-01-03 04:34

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...

3条回答
  •  庸人自扰
    2021-01-03 05:25

    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.

提交回复
热议问题