我用到处找到的零件做的,效果很好
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MainClass {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField nameTextField = new JTextField();
frame.add(nameTextField, BorderLayout.NORTH);
KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent keyEvent) {
printIt("Pressed", keyEvent);
}
public void keyReleased(KeyEvent keyEvent) {
//printIt("Released", keyEvent);
}
public void keyTyped(KeyEvent keyEvent) {
//printIt("Typed", keyEvent);
}
private void printIt(String title, KeyEvent keyEvent) {
int keyCode = keyEvent.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode);
System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar() + " code = " + keyEvent.getKeyCode());
}
};
nameTextField.addKeyListener(keyListener);
frame.setSize(250, 100);
frame.setVisible(true);
}
}
只需运行它,按一个键并查看您的 Eclipse 控制台