GUI笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/StillOnMyWay/article/details/76652494

2017-07-17

  1. GUI中,监听器一般都有适配器,各种listener接口,由于需要复写较多方法,所以有一个便于创建对象的子类,我们只需要复写自己需要的方法即可。如WindowAdapter,MouseAdapter。
  2. Button的mouseListener优先于actionListerner执行。键盘也可以让Button活动执行actionListerner。
  3. MouseEvent类里面封装了许多方法,不如getClickCount(),获取鼠标点击的次数。

  4. 键盘输入屏蔽非数字

        import java.awt.*;
        import java.awt.event.*;

        class FrameDemo {
            private Frame f;
            private Button b;
            private TextField tf;

            FrameDemo() {
                initi();
            }

            //窗体和组件的初始化单独封装
            private void initi() {
                f = new Frame("帅气的Frame!!!");
                System.out.println(f.getTitle());

                f.setLocation(500,300);
                f.setSize(500,300);

                b = new Button("我是一个帅气的Button");

                tf = new TextField(20);

                f.setLayout(new FlowLayout());
                f.add(b);
                f.add(tf);

                myEvent();      

                f.setVisible(true);
            }

            //将注册事件封装到单独的方法里面
            private void myEvent() {

                f.addWindowListener(new WindowAdapter(){
                    public void windowClosing(WindowEvent e){
                    System.out.println("我他妈的帅扎天");
                    System.exit(0);
                    }
                });

                b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("我他妈的就是帅扎天");
                    }
                });

                //按下的键盘返回对应的int数值,KeyEvent类中已经封装好了静态的各种常量对应键盘上的按键
                tf.addKeyListener(new KeyAdapter(){
                    public void keyPressed(KeyEvent e){
                        int key = e.getKeyCode();
                        if (!(key >= KeyEvent.VK_0 && key <= KeyEvent.VK_9)) {
                          e.consume();  // 之后默认的输入方法不执行,反映出来就是只有数字会显示到文本域中,其他按键不行。
                        }
                    }
                });
            }

            public static void main(String[] args) {
                    new FrameDemo();
            }
        }

猜你喜欢

转载自blog.csdn.net/StillOnMyWay/article/details/76652494
GUI