首页 > 解决方案 > 从 GWT 中的不同小部件触发处理程序事件

问题描述

我有两个 ListBox,假设customerListBoxtimeListBox和 Label resultLabel。当timeListBox' 的值发生变化时,它会触发它ValueChangeHandler(我们称之为recalculateValueHandler),它重新计算结果并将其放入resultLabel. 我需要反之亦然 - 当customerListBox' 的值发生变化时,我需要为相同的时间值但不同的客户重新计算新结果。所以我需要类似的东西customerListBox.onValueChange(fire(recalculateValueHandler)),希望你能理解。有什么可以以这种方式对我有用吗?我尽量避免将几乎相同的代码复制到两个处理程序中。

标签: javagwt

解决方案


你只需要三样东西

  • 在顶层声明所有元素,以便它们可以在所有方法中访问
  • 创建一个重新计算值的方法,我们称之为recalculateValue
  • 为将调用方法ChangeHandler的两个ListBoxes(ListBox没有)添加s。ValueChangeHandlerrecalculateValue

工作示例:

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;

public class Test implements EntryPoint {

    // elements declared at top level are accessible across all methods
    private ListBox customerListBox;
    private ListBox timeListBox;
    private Label resultLabel;

    @Override
    public void onModuleLoad() {
        // add some data
        customerListBox = new ListBox();
        for(int i = 0; i < 10; i++)
            customerListBox.addItem("Customer " + (i + 1));

        // add some data
        timeListBox = new ListBox();
        for(int i = 0; i < 10; i++)
            timeListBox.addItem("Time " + (i + 1));

        resultLabel = new Label();
    
        // recalculateValue when customerListBox changes
        customerListBox.addChangeHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent event) {
                recalculateValue();
            }
        });
    
        // recalculateValue when timeListBox changes
        timeListBox.addChangeHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent event) {
                recalculateValue();
            }
        });

        // initial result (optional)
        recalculateValue();

        // show elements
        RootPanel.get().clear();
        RootPanel.get().add(customerListBox);
        RootPanel.get().add(timeListBox);
        RootPanel.get().add(resultLabel);
    }

    private void recalculateValue() {
        // use values from ListBoxes
        resultLabel.setText(customerListBox.getSelectedValue() + " / " + timeListBox.getSelectedValue());
    }
}

请注意,两个处理程序是相同的,因此您只能创建一个处理程序并将其用于两个ListBoxes,如下所示:

ChangeHandler handler = new ChangeHandler() {
    @Override
    public void onChange(ChangeEvent event) {
        recalculateValue();
    }
};

// recalculateValue when customerListBox changes
customerListBox.addChangeHandler(handler);

// recalculateValue when timeListBox changes
timeListBox.addChangeHandler(handler);

推荐阅读