java全局键盘监听器

class ImplAWTEventListener implements AWTEventListener {  
    @Override  
    public void eventDispatched(AWTEvent event) {  
    	if (event.getClass() == KeyEvent.class) {  
    		// 被处理的事件是键盘事件.  
            KeyEvent keyEvent = (KeyEvent) event;
            if (keyEvent.getID() == KeyEvent.KEY_PRESSED) {
                keyPressed(keyEvent);  
            } else if (keyEvent.getID() == KeyEvent.KEY_RELEASED) {  
                //放开时你要做的事情  
                keyReleased(keyEvent);  
            }  
        }  
    }  
    private void keyPressed(KeyEvent keyEvent) {}
    private void keyReleased(KeyEvent event) {}
}  

在需要添加监听器的地方插入以下代码:

Toolkit tk = Toolkit.getDefaultToolkit();  
tk.addAWTEventListener(new ImplAWTEventListener(), AWTEvent.KEY_EVENT_MASK);  

你可能感兴趣的:(学习笔记)