简体   繁体   English

如何在同一方法中添加KeyPressed事件

[英]How to add KeyPressed Event in the same method

I have a problem with this code: 我有这个代码的问题:

 CaptachaKey.addKeyListener(new KeyAdapter()
    {
        public void KeyPressed(KeyEvent e)
        {
            System.out.println("It works!" + e.getKeyCode());
            if (e.getKeyCode() == 10)
            {
                text = CaptachaKey.getText();
                f.setVisible(false);

            }
        }
    });

It doesn't work... How can I add this listener in the same class? 它不起作用......如何在同一个类中添加此侦听器?

Instead of using KeyListener use KeyBindings , for example for code 10: 而不是使用KeyListener使用KeyBindings ,例如代码10:

  getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"), "doSomething");
  getActionMap().put("doSomething",new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            System.out.println("profit");
        }
    });

According to your code : 根据你的代码:

CaptachaKey.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"), "doSomething");
CaptachaKey.getActionMap().put("doSomething",new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            text = CaptachaKey.getText();
            f.setVisible(false);
        }
    });

And when you press ENTER key, your code will be executed. 当您按ENTER键时,您的代码将被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM