如何在Java程序内实现键盘监听?

 

package  com.bovy.ui;

import  java.awt.KeyboardFocusManager;

import  javax.swing.JFrame;

public   class  KeyboardListener  extends  JFrame  {

    
/**
     * Launch the application
     * 
     * 
@param args
     
*/

    
public static void main(String args[]) {
        
try {
            KeyboardListener frame 
= new KeyboardListener();
            frame.setVisible(
true);
        }
 catch (Exception e) {
            e.printStackTrace();
        }

    }


    
/**
     * Create the frame
     
*/

    
public KeyboardListener() {
        
super();
        setTitle(
"在Java内实现键盘监听");
        setBounds(
100100500375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
//
        KeyboardFocusManager manager = KeyboardFocusManager
                .getCurrentKeyboardFocusManager();
        manager.addKeyEventPostProcessor(
new MyKeyEventPostProcessor());
    }

}

 

 

package  com.bovy.ui;

import  java.awt.KeyEventPostProcessor;
import  java.awt.event.KeyEvent;

public   class  MyKeyEventPostProcessor  implements  KeyEventPostProcessor  {
    
public boolean postProcessKeyEvent(KeyEvent event) {
        System.out.println(KeyEvent.getKeyText(event.getKeyCode()));
        
return true;
    }

}

你可能感兴趣的:(如何在Java程序内实现键盘监听?)