Is there a standard class for events in Java?

I wrote a listener. Now I want to notify you when a change occurs. Nothing special.

Now I ask myself: Do I have a standard class for events that I can use, or do I need to write a new one?

I know ara java.awt.Event and AWTEvent. But I do not work directly at the GUI level here. In addition, we use Swing at the GUI level. So I'm not sure if mixing Swing and AWT is a good idea.

thanks

+3
source share
6 answers

Its ancient and simple, but you can use Observer / Observerable in java.util:

java.util

public class Observable extends Object

"" . , .

. , . , , notifyObservers .

http://www.javaworld.com/javaworld/jw-10-1996/jw-10-howto.html.

+4

Java . GUI, , java.awt.Events.

+2

, EventBus:

- / , Swing. EventBus , API (80 +%). , , .

+2

EventObject . JavaDoc:

, .

, "", , .

+2

Swing - , . , . - ( ):

class SomeClassInWhichTheEventOccurs {
    List<MyListener> listeners;
    void addListener(listener) { listeners.add(listener); }
    void removeListener(listener) { listeners.remove(listener); }
    void fireEvent(someEventParameters) {
        foreach (listener in listeners) listener.eventOccured();
    }
    void someMethodInWhichTheEventOccurs() {
       ...
       fireEvent(someEventParameters);
    }
}

: , java.awt.Event .

+1

Swing is based on AWT, so you should mix it. The problem is mixing AWT heavyweight components with lightweight Swing components. Do not use AWT heavy components.

Just to be notified that something has changed javax.swing.event.ChangeListeneris ok. In fact, until you use a library that assumes the beans model, you can ignore event classes and use an observer without an event object.

0
source

Source: https://habr.com/ru/post/1710172/


All Articles