本文共 3589 字,大约阅读时间需要 11 分钟。
- package testCustomEvent;
-
- import javax.swing.event.EventListenerList;
- import java.util.Date;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
-
- public class MyEventTestNew implements MyListener{
- public static void main(String[] args){
- MySource source = new MySource();
-
- ActionListener al=new ActionListener(){
-
- @Override
- public void actionPerformed(ActionEvent e) {
-
- System.out.println("allllllllllllllll");
- }
-
- };
-
- MyEventTestNew mtn=new MyEventTestNew();
- source.addMyListener(mtn);
- source.addMyListener(al);
- source.doSomething();
- }
-
- @Override
- public void doMyAction(MyEvent e) {
- System.out.println("listener detects " + e);
-
- }
- }
-
- class MyEvent extends java.util.EventObject{
- private Date date;
-
- public MyEvent(Object source , Date date){
- super(source);
-
- this.date = date;
- }
-
- public String toString(){
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String dt = df.format(date);
-
- return "[event]:" + super.toString() + " [occur at]:" + dt;
- }
- }
-
- interface MyListener extends java.util.EventListener{
- void doMyAction(MyEvent e);
- }
-
- class MySource{
-
- protected EventListenerList listenerList = new EventListenerList();
- private MyEvent myEvent = null;
-
-
- public MySource(){
- }
-
- public void addMyListener(MyListener listener){
- listenerList.add(MyListener.class , listener);
- }
-
-
- public void addMyListener(ActionListener al){
- listenerList.add(ActionListener.class , al);
- }
-
-
- public void removeMyListener(MyListener listener){
- listenerList.remove(MyListener.class , listener);
- }
-
-
- public MyListener[] getMyListeners(){
- return (MyListener[])listenerList.getListeners(MyListener.class);
- }
-
-
- */
- protected void fireDoMyAction() {
-
- Object[] listeners = listenerList.getListenerList();
-
-
- for (int i = listeners.length-2; i>=0; i-=2) {
- if (listeners[i]==MyListener.class) {
-
- if (myEvent == null)
- myEvent = new MyEvent(this , new Date());
- ((MyListener)listeners[i+1]).doMyAction(myEvent);
- } else if(listeners[i]==ActionListener.class) {
- System.out.println("hahahahahaha");
- }
- }
- }
-
-
- public void doSomething() {
- System.out.println("do something interesting here.");
-
- fireDoMyAction();
- }
- }
转载于:https://www.cnblogs.com/ygzs007/p/9041768.html