-1

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

public class TypeHelperMain extends Thread implements KeyListener    
    {


        public TypeHelperMain(){

            addKeyListener(this);

        }
4

1 回答 1

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/

于 2013-09-14T14:04:23.647 回答