如何将keyListener添加到扩展Thread的类

时间:2013-09-14 13:37:44

标签: java eclipse multithreading awt keylistener

线程不包含名为addKeyListener()的方法,但有没有办法将addKeylistener方法添加到线程?我需要听一下击键。

public class TypeHelperMain extends Thread implements KeyListener    
    {


        public TypeHelperMain(){

            addKeyListener(this);

        }

1 个答案:

答案 0 :(得分:1)

如果您尝试在Swing应用程序中执行此操作,那么我建议使用此方法:

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
        new KeyEventDispatcher() {
            public boolean dispatchKeyEvent(KeyEvent keyEvent) {
                if(keyEvent.getID() == KeyEvent.KEY_TYPED) {
                    System.out.println("Captured: " + keyEvent.getKeyCode());
                }
                return false; // allowing it to be dispatched further
            }
        });

来源:http://portfolio.planetjon.ca/2011/09/16/java-global-jframe-key-listener/