简体   繁体   English

JavaFX事件/侦听器/处理程序

[英]JavaFX events/listeners/handlers

I have 2 listViews and 2 custom controls on my scene. 我的场景中有2个listViews和2个自定义控件。 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. 当我在listView中按一个项目时,我想引发该事件,然后能够在应用程序中的其他任何地方进行处理。 Ideally i would like my 2 custom controls to listen for this event, and handle it when it is raised. 理想情况下,我希望我的2个自定义控件侦听此事件,并在引发事件时进行处理。

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? 这是我的自定义事件,我也想传递一个关于哪个Offer的参数,但是不确定如何执行此操作?

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???
        }
    });

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: 对于您的情况,大约有3种不同的方式连接应用程序,以便不同的部分可以对其他部分的更改做出反应:

  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 您可以尝试这个https://github.com/bennidi/mbassador

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM