5

I am working on implementing a ListBox that I want to be able to alert the user when they make a selection in the ListBox. Is there a way to respond to the user clicking an item in the listbox, and respond to the selection before a "changeEvent" occurs so I can prevent the changeEvent from getting fired. I have tried using

Event.addNativePreviewHandler(new NativePreviewHandler() {
   @Override
   public void onPreviewNativeEvent(NativePreviewEvent event) {
      System.out.println("EVENT: " + event.getTypeInt());
   }
});

but this never responds to clicking on a specific element in the ListBox, it only responds to clicking on the ListBox initially, when you focus the ListBox. I want to be able to do something like:

Event.addNativePreviewHandler(new NativePreviewHandler() {
   @Override
   public void onPreviewNativeEvent(NativePreviewEvent event) {
      if(event is changeEvent && event source is listBox) {
          if(do some check here)
             event.stopPropagation();
      }
   }
});

Any suggestions would be greatly appreciated, thanks!

4

3 回答 3

3

谢谢各位的意见。我最终做的是在列表框获得焦点时保存选择的状态。并保存此索引并在 changeEvent 发生时切换它,仅在允许的情况下将其更改为下一个选择。

@UiHandler("listBox")
public void onListBoxFocus(FocusEvent event) {
   this.saveListBoxSelection = listBox.getSelectedIndex();
}

@UiHandler("listBox")
public void onChange(ChangeEvent event) {
   int newSelection = listBoxCompliant.getSelectedIndex();
   listBox.setSelectedIndex(this.saveListBoxSelection);
   if(proceed with change)
      listBox.setSelectedIndex(newSelection);
   else 
      //cancel event

这是使用 uibinder 完成的,但也可以通过简单地将此事件直接添加到 listBox 来完成。再次感谢您的评论!

于 2012-09-26T20:03:10.910 回答
3

如果您不想处理它,您可以简单地杀死该事件:

@Override
onChange(ChangeEvent event) {
    // ask user if he wants to continue
    // if yes
       doSomething();
    // if no
       event.kill();
}
于 2012-09-25T21:23:27.467 回答
1

允许 ChangeEvent 继续并没有什么坏处。您可以将逻辑添加到 ChangeEvent 处理程序。如果用户决定不继续,您只需将选择设置回前一个或删除选择。

@Override
onChange(ChangeEvent event) {
    // ask user if he wants to continue
    // if yes
       doSomething();
    // if no
       myList.setSelectedIndex(-1);
} 
于 2012-09-25T21:20:25.470 回答