从GWT中的不同小部件激发处理程序事件



我得到了两个ListBox,假定为customerListBoxtimeListBox,并标记为resultLabel。当timeListBox的值更改时,它会触发ValueChangeHandler(我们称之为recalculateValueHandler(,后者会重新计算结果并将其放入resultLabel中。我需要这样做,反之亦然——当customerListBox的值更改时,我需要为相同的时间值但不同的客户重新计算新的结果。所以我需要customerListBox.onValueChange(fire(recalculateValueHandler))这样的东西,希望你能理解。有什么可以这样对我有用的吗?我尽量避免将几乎相同的代码复制到两个处理程序中。

只需要三样东西

  • 在顶级声明所有元素,以便所有方法都可以访问这些元素
  • 创建一个重新计算值的方法,称之为recalculateValue
  • 为将调用recalculateValue方法的两个ListBox添加ChangeHandlers(ListBox没有ValueChangeHandler(

工作示例:

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

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

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

最新更新