- //GUIawtMouseEvent.java
- import java.awt.*;
- import java.awt.event.*;
- class GUIawtKeyEvent{
- public static void main(String[] args){
- new FrameDemo();
- }public static void sop(Object obj){
- System.out.println(obj);
- }
- }
- class FrameDemo{
- private Frame f;
- private Button b;
- private TextField tf;
- FrameDemo(){
- init();
- }
- public void init(){
- f=new Frame("hello");
- f.setVisible(true);
- f.setSize(500,120);
- f.setLocation(350,150);
- f.setLayout(new FlowLayout());
- b=new Button("完成退出");
- f.add(b);
- tf=new TextField(10);
- f.add(tf);
- myEvent();
- }private void myEvent(){
- //为窗口创建监听器
- f.addWindowListener(new WindowAdapter(){
- public void windowClosing(WindowEvent e){
- System.out.println("closing");
- System.exit(0);
- }
- });
- //为创建按钮监听器
- b.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- System.out.println("exiting,button");
- System.exit(0);
- }
- });
- //创建键盘监听器
- b.addKeyListener(new KeyAdapter(){
- public void keyPressed(KeyEvent e){
- if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER)//组合键
- System.exit(0);
- System.out.println(e.getKeyChar()+" "+e.getKeyText(e.getKeyCode()));
- }
- });
- tf.addKeyListener(new KeyAdapter(){
- public void keyPressed(KeyEvent e){
- int code=e.getKeyCode();
- if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9)){
- System.out.println(code+" is 非法字符");
- e.consume();
- }
- }
- });
- }
- }
- 文本框里输出“非法字符“后依然显示在文本框里,我哪里写错了,自己检查不错错因
复制代码 |