如何在GWT中调用单个eventhandler类中编写的相应Java方法(对于每个按钮)?

时间:2013-04-09 20:34:32

标签: java gwt jsni

我想在点击不同的按钮时调用不同的方法(在单个GWT事件处理程序类中)?就像这样:

假设我的UI中有3个按钮:

  1. Button1的
  2. 将Button2
  3. 将Button3
  4. 而且,我为每个人添加了相同的(Click)EventHandler:ButtonClicker

    在OnClick()方法中,我想调用与单击的按钮对应的方法。这里有一些示例代码,可以更好地说明我要做的事情:

    public class ButtonClicker implements ClickHandler 
    {
        public void onClick(ClickEvent event)
        {
            PushButton clickedButton = (PushButton) event.getSource();
    
            // I could call the corresponding method using if-else condition but I do not want to do that. 
            // Instead, I want some code here, may be using JSNI (using eval in some way) or something like that to call the corresponding method.
            ......      
        }
    
        private void Button1Click()
        {
            // Code to handle Button1 Click 
        }
    
        private void Button2Click()
        {
            // Code to handle Button2 Click
        }
    
        private void Button3Click()
        {
            // Code to handle Button3 Click
        }
    }
    

    提前致谢。

1 个答案:

答案 0 :(得分:2)

我认为你有充分的理由去这条错综复杂的路线,所以这是一个提案,不包含任何判断:

JavaScriptObject map = createMap(this);

private static native JavaScriptObject createMap(ButtonClicker o) /*-{
   // Note: does not use $entry() as this will be called from GWT code
   return {
       "button1": function() { o.@foo.ButtonClicker::Button1Click()(); },
       "button2": function() { o.@foo.ButtonClicker::Button2Click()(); },
       "button3": function() { o.@foo.ButtonClicker::Button3Click()(); }
     };
}-*/;

private static native void call(JavaScriptObject map, String id) /*-{
  var fn = map[id];
  // TODO: add null-check / fallback behavior
  fn();
}-*/;

@Override
public void onClick(ClickEvent event) {
  call(map, ((UIObject) event.getSource()).getElement().getId());
}