首页 > 学院 > 开发设计 > 正文

java—监听器 (55)

2019-11-15 00:04:05
字体:
来源:转载
供稿:网友
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=obj;

}

public Object getSource(){

return src;

}

}

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表