KeyPressed event in java

后端 未结 3 1763
南笙
南笙 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:07

    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.

提交回复
热议问题