Alternate of C# Events in Java

后端 未结 4 1806
迷失自我
迷失自我 2020-12-24 02:55

I am .Net developer. i want to know that is there any event handling mechanism in Java for Events Handling like C#.

what i want to do is i want to raise/fire an even

相关标签:
4条回答
  • 2020-12-24 03:43

    Check out this tutorial. It goes through some of the Swing event handling stuff that you have come across in your searches, but the concepts are pretty general. In simple terms, event handlers maintain a collection of listeners (implementing an interface) and iterate over them when they fire an event, calling the method in the interface.

    0 讨论(0)
  • 2020-12-24 03:48

    Although most of the examples will be to do with GUI events, the principles are basically the same. You basically want an interface or abstract class to represent a handler for the event, e.g.

    public interface EventHandler
    {
        // Change signature as appropriate of course
        void handleEvent(Object sender, EventArgs e);
    }
    

    then the publisher of the event would have:

    public void addEventHandler(EventHandler handler)
    public void removeEventHandler(EventHandler handler)
    

    It would either keep a list of event handlers itself, or possibly have them encapsulated in a reusable type. Then when the event occurs, you just call handleEvent in each handler in turn.

    You can think of delegate types in C# as being very similar to single-method interfaces in Java, and events are really just an add/remove pair of methods.

    0 讨论(0)
  • 2020-12-24 03:53

    I love C# Events,

    They are simple to use and convenient. i missed them in java so wrote a small utility class that mimics the very basics of C# Event.

    • using java 8 (for lambdas)
    • no += operator, instead call .addListener((x) -> ...)
    • to trigger an event, call .broadcast(<EventArgs insance>)

    Online Demo - https://repl.it/DvEo/2


    Event.java

    import java.util.HashSet;
    import java.util.Set;
    import java.util.function.Consumer;
    
    public class Event {
        private Set<Consumer<EventArgs>> listeners = new HashSet();
    
        public void addListener(Consumer<EventArgs> listener) {
            listeners.add(listener);
        }
    
        public void broadcast(EventArgs args) {
            listeners.forEach(x -> x.accept(args));
        }
    }
    
    • You may want com.google.common.collect.Sets.newConcurrentHashSet() for thread safety

    EventArgs.java

    public class EventArgs {
    }
    
    0 讨论(0)
  • 2020-12-24 03:54

    Java has support through various event handling implementations - the simple Observer/Observable in java.util, PropertyChangeEvents in java.beans, and GUI events which inherit from AWTEvent.

    An Observable object has a list of observers which implement the Observer interface, and mechanisms for adding and removing observers. If o.notifyObservers(x) is called on the observable, update(o,x) will be called on each observer. This mechanism is somewhat old fashioned and rarely used in new code - it dates from Java 1.0 before EventObject was added in Java 1.1 and better event handling added for AWT and beans.

    Beans and GUI events propagate an object which extends java.util.EventObject to listeners which implement a sub-interface of EventListener. Usually if you're using an existing API you will only care about the events and listeners for that API, but if you're defining an API the events and listeners should follow that convention.

    It's also the convention in Java APIs to call the handlers for events "listeners" rather than handlers, and all listener interface names end with Listener. The names of the methods don't start with 'on' but should be past tense -mouseMoved or handshakeCompleted rather than onMouseMove or handleMouseMove.

    The PropertyChangeSupport class provides an implementation of the mechanism for adding and removing listeners from a bean, and is also used for properties of Swing widgets.

    If you write your own listener handling, it's conventional to allow listeners to remove themselves by calling source.removeXXXListener(this) from within their event handling method. Just iterating over a simple collection of listeners and calling their handling methods would give a ConcurrentModificationException with in these cases - you need to copy the collection of listeners or use a concurrently modifiable collection.

    0 讨论(0)
提交回复
热议问题