java - 从 GWT 中的不同小部件触发处理程序事件
问题描述
我有两个 ListBox,假设customerListBox
和timeListBox
和 Label resultLabel
。当timeListBox
' 的值发生变化时,它会触发它ValueChangeHandler
(我们称之为recalculateValueHandler
),它重新计算结果并将其放入resultLabel
. 我需要反之亦然 - 当customerListBox
' 的值发生变化时,我需要为相同的时间值但不同的客户重新计算新结果。所以我需要类似的东西customerListBox.onValueChange(fire(recalculateValueHandler))
,希望你能理解。有什么可以以这种方式对我有用吗?我尽量避免将几乎相同的代码复制到两个处理程序中。
解决方案
你只需要三样东西
- 在顶层声明所有元素,以便它们可以在所有方法中访问
- 创建一个重新计算值的方法,我们称之为
recalculateValue
- 为将调用方法
ChangeHandler
的两个ListBox
es(ListBox
没有)添加s。ValueChangeHandler
recalculateValue
工作示例:
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
es,如下所示:
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);
推荐阅读
- asp.net-core-3.1 - 如果用户是 ASP.NET Core 3.1 MVC 中的管理员,则有条件地呈现 HTML 内容的最佳方式
- r - 如何将全局环境中的列表数据获取到列表中
- python - 加载到 Google Colab 后获取文件名
- java - maven“churchofjesuschrist.org”问题
- javascript - 使用 .push 更新对象以添加新元素
- node.js - 中间件实现不适用于某些路由
- java - 新聊天消息的 Firebase 推送通知
- mysql - 有人成功从 XWIKI ENTERPRISE 5.0-MILESTONE-2 迁移到 12.3 版吗?
- c# - UWP - 在初始文件夹中禁用 FolderPicker 提交按钮
- go - 无法使用 VALID 密钥验证有效令牌