import java.awt.Button; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.TextField; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class MouseAndKeyDemo { private Frame f; private TextField tf; private Button but; public MouseAndKeyDemo() { init(); } private void init() { f = new Frame("演示鼠标和键盘监听"); f.setBounds(400,200,500,400); f.setLayout(new FlowLayout()); tf = new TextField(35); but = new Button("一个按钮"); f.add(tf); f.add(but); myEvent(); f.setVisible(true); } private void myEvent() { //给文本框添加键盘监听。 tf.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { // System.out.println("key run..."+KeyEvent.getKeyText(e.getKeyCode())+"::::"+e.getKeyCode()); // int code = e.getKeyCode(); // if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9)){ // System.out.println("必须是数字"); // e.consume(); // } if(e.isControlDown() && e.getKeyCode()==KeyEvent.VK_ENTER){ System.out.println("enter run ..."); } } }); } public static void main(String[] args) { new MouseAndKeyDemo(); } }