Event Listeners in Java

后端 未结 5 564
陌清茗
陌清茗 2021-02-06 03:44

I\'ve been working with event listeners in AS3, but seems like there is none in java (except for graphics components). It\'s surprising.

The question is, how could i imp

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 03:46

    You can define a Listener interface:

    public interface EventListener {
        void fireEvent (Event e);
    }
    

    Then in your code:

    EventListener lst = new EventListener() {
        @Override
        public void fireEvent (Event e) {
            //do what you want with e
        }
    }
    
    someObject.setListener(lst);
    someObject.somethingHappened();
    

    Then in someObject (in practice you would probably hold a list of listeners):

    public class SomeObject {
        private EventListener lst;
    
        public void setListener (EventListener lst) {
            this.lst = lst;
        }
    
        public void somethingHappened () {
            lst.fireEvent(new Event("Something Happened"));
        }
    }
    

提交回复
热议问题