0

Let's say I have a (NOT so super duper) class:

public class MySuperDuperClass {
    int myField1 = 0;
    String myField2 = "1";
}

Is there a way for my class to register an event handler, and handle the specified event type after the event is fired from somwhere in application? Something like javafx.scene.Node does?

For example:

public class MyEvent extends Event {

    public static final EventType<MyEvent> SUPER_DUPER_EVENT = new EventType<>("SUPER_DUPER_EVENT");

    private final String msg;

    public MyEvent(String msg) {
        super(SUPER_DUPER_EVENT);
        this.msg = msg;
    }

    public String getMessage() {
        return msg;
    }

}

public class MyEventHandler implements EventHandler<MyEvent> {
    @Override
    public void handle(MyEvent event) {
        System.out.println(event.getMessage());
    }
}

With Node and it's subclasses I can do:

Node node = // omitted
node.addEventHandler(MyEvent.SUPER_DUPER_EVENT, new MyEventHandler());

What is the best way (if any) to acomplish this with my class?

Maybe one of these:

Of course, one can always say to extend Node class, but my class has nothing to do with node and I would like NOT to complicate "architecture" even further.

EDIT #1: Basically, I just want for instance of my class to be able to detect MyEvent which is fired from anywhere in the JavaFX application:

// At boot...
MySuperDuperClass myInstance = new MySuperDuperClass();
myInstance.addEventHandler(MyEvent.SUPER_DUPER_EVENT, new MyEventHandler());

// Somewhere, at unspecified time app would fire MyEvent
Event event = new MyEvent("Firing the event in 3... 2... 1...");
Event.fireEvent(myInstance, event);    // or any other way to fire event globally so it can be registered by myInstance...
Community
  • 1
  • 1
zkristic
  • 629
  • 1
  • 9
  • 24

1 Answers1

1

something like this?

public class MyNotSuperDuperClass {

public MyNotSuperDuperClass(Stage theParentStageOfMyApplication){
     theParentStageOfMyApplication.addEventFilter(MyEventType, new EventHandler<MyEvent>() {
        @Override
        public void handle(MyEvent t) {             
            t.getSource(); //the person who fired the event
            t.getEventTarget();//the person who is receiving the event
        }
    });
}
...

now your class can pretty much listen to all Event that your application fires on that Event

hope it was helpful

Elltz
  • 10,730
  • 4
  • 31
  • 59
  • Yep, it works... I don't know how I didn't think of using dependency injection instead of extending class that I don't need. Thanks! – zkristic Aug 06 '16 at 16:13