为什么如果我们将 HandlerRegistration 放入一个方法中,那么我们就不能删除 Handler?



好的,我有很多复选框,当程序第一次运行时,它将对所有复选框addClickHandler,当我重置程序时,我想清除所有处理程序。

这是示例代码;

 private HandlerRegistration countryHandlerReg=null;
 private HandlerRegistration postCodeHandlerReg=null;
 public void resetVariables(){
        if(postCodeHandlerReg!=null){
            postCodeHandlerReg.removeHandler();
        }
        if(countryHandlerReg!=null){
            countryHandlerReg.removeHandler();
        }
 }
 public void addClickHandlerForCheckBox(HandlerRegistration handlerReg, CheckBox myCheckBox){
        handlerReg=myCheckBox.addClickHandler(new MyClickHandler(myCheckBox));
 }
 public void showData(){
     resetVariables();
     addClickHandlerForCheckBox(postCodeHandlerReg, getView().getPostCodeCheckBox());
     addClickHandlerForCheckBox(countryHandlerReg, getView().getCountryCheckBox());
 }

有一个按钮可以调用showData()

上面的代码无法正常工作,因为它无法运行.removeHandler()所以如果我单击按钮 2 或 3 次,那么每个复选框将有 2 或 3 个MyClickHandler()

但是,如果我在不使用方法addClickHandlerForCheckBox的情况下像这样更改showData(),那么它可以正常运行:

public void showData(){
     resetVariables();
     postCodeHandlerReg= getView().getPostCodeCheckBox().addClickHandler(new MyClickHandler(getView().getPostCodeCheckBox()));
 ....
 }

所以我认为如果我使用addClickHandlerForCheckBox方法,那么它就无法删除处理程序。

你知道为什么吗?还是我做错了什么?

做这样的更改,它会删除处理程序

public HandlerRegistration addClickHandlerForCheckBox(CheckBox myCheckBox) {
 return myCheckBox.addClickHandler(new MyClickHandler(myCheckBox));
}
public void showData() {
  resetVariables();
  postCodeHandlerReg = addClickHandlerForCheckBox(postCode);
 countryHandlerReg = addClickHandlerForCheckBox(country);
}

对于 JCheckBox,您可以像这样添加和删除侦听器:

public static void main(String [] args)
{
    JCheckBox checkBox = new JCheckBox();
    checkBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent arg0) {
            // TODO Auto-generated method stub
        }
    });
    ItemListener [] itemListeners = checkBox.getListeners(ItemListener.class);
    System.out.println(itemListeners.length);
    for (int i = 0; i < itemListeners.length; i++)
    {
        checkBox.removeItemListener(itemListeners[i]);
    }
    System.out.println(checkBox.getListeners(ItemListener.class).length);
}

看起来您正在使用一些自定义类。 因此,如果此示例没有帮助,您可能需要发布 addClickHandler 和 removeHandler 的代码。

我假设您在CheckBox上保留了一个处理程序列表,因此您可以添加一些方法,例如CheckBox.removeListeners,该方法仅清除列表。

相关内容

最新更新