java—监听器 (55)

王朝学院·作者佚名  2016-05-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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;

}

}

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航