Gillardo
Gillardo

Reputation: 9818

JavaFX events/listeners/handlers

I have 2 listViews and 2 custom controls on my scene. When i press on an item in the listView, i would like to raise the event, and then be able to handle this anywhere else in the application. Ideally i would like my 2 custom controls to listen for this event, and handle it when it is raised.

Not sure if this is right, but so far i have this

Here is my custom event, i would also like to pass in an argument of which Offer is it, not sure how to do this though?

public class OfferChangedEvent extends Event {

    private static final long serialVersionUID = 1L;

    public static final EventType<OfferChangedEvent> OFFER_CHANGED = new EventType<OfferChangedEvent>(ANY, "OFFER_CHANGED");

    public OfferChangedEvent() {
        this(OFFER_CHANGED);
    }

    public OfferChangedEvent(EventType<? extends Event> arg0) {
        super(arg0);
    }
    public OfferChangedEvent(Object arg0, EventTarget arg1, EventType<? extends Event> arg2) {
        super(arg0, arg1, arg2);
    }  
}

Now on one of my custom controls, i raise the event when a button is clicked, like so

@FXML
public void showOffer(ActionEvent event) {
    Button btnView = (Button)event.getSource();

    // can i pass in parameter of the offer here??
    btnView.fireEvent(new OfferChangedEvent());
}

Now i would like a listview to listen for the event and handle it, i have this but it aint working

    // when offer is changed, we dont want to see events
    this.eventListPane.addEventHandler(OfferChangedEvent.OFFER_CHANGED, new EventHandler<OfferChangedEvent>() {

        @Override
        public void handle(OfferChangedEvent event) {
            Console.Log("Recived");
            eventListPane.setVisible(false);
            // How can i get the argument of the offer passed???
        }
    });

Upvotes: 0

Views: 371

Answers (1)

Jurgen
Jurgen

Reputation: 2154

Unfortunately there isn't a straightforward answer to this question. For your case there are about 3 different ways to wire up your application so that different parts can react to changes in other parts:

  1. You could bind to properties and listen for changes.
  2. You could setup listeners and then notify them of changes.
  3. You could use a messaging bus.

Which one you use depends on various factors, but considering what you have done above I would go with number three. You can try this https://github.com/bennidi/mbassador

Upvotes: 1

Related Questions