星空网 > 软件开发 > Java

java—监听器 (55)

**存在以下对象

监听者:XxxxxListener - 所的监听者是的接口

被监听者 :任意对象都可以成为被监听者 - 早已经存在。

监听到的事件:XxxxEvent- 永远是一个具体类,用来放监听到的数据

                            里面都有一个方法叫getSource() – 返回的是监听到对象。

案例一:

package cn.hx.demo;

public class MyFrame extends JFrame {

    public MyFrame() {

        JButton btn = new JButton("你好");  //被监听者

        System.err.println("btn: is:"+btn.hashCode());

        btn.addActionListener(new MyListener() ); //监听者

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //获取容器

        Container con= getContentPane();

        //设置布局

        con.setLayout(new FlowLayout());

        con.add(btn);

        setSize(300, 300);

        setVisible(true);

    }

    public static void main(String[] args) {

        new MyFrame();

    }

    //实现一个监听者

    class MyListener implements ActionListener{

        //监听方法

        public void actionPerformed(ActionEvent  e) {

            System.err.println("我监听到了:"+e.getSource()hashCode());  //可以从监听到的事件中获监听到的对象。

        }

    }

}


案例二:

观察者模式模拟监听

package cn.hx.demo;

public class TestObersver {

    public static void main(String[] args) {

        Person person = new Person();//声明被观察者

        System.err.println("pp:"+person);

        person.addPersonListener(new PersonListener() {

            public void running(PersonEvent pe) {

                System.err.println("你正在跑....."+pe.getSource());

                throw new RuntimeException("他跑了。。。");

            }

        });

        person.run();

    }

}

class Person{

    private PersonListener pl;

    public void addPersonListener(PersonListener pl){

        this.pl = pl;

    }

    public void run(){

        if(pl!=null){

            pl.running(new PersonEvent(this));

        }

        System.err.println("我正在跑步......");

    }

}

interface PersonListener{

    void running(PersonEvent pe);

}

class PersonEvent{

    private Object src;

    public PersonEvent(Object obj) {

        this.src='/images/loading.gif' data-original=obj;

    }

    public Object getSource(){

        return src;

    }

}


 与上面的案例一进行对比,体会**做了什么。


 


 






原标题:java—监听器 (55)

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流