2010-02-16 108 views
1

我正在动态创建一个MenuItem,并且我想在单击MenuItem时添加一个自定义监听器。JSF添加动作监听器

我试着添加addActionListener和setActionListener,但当链接被点击时,这些都不会被调用。

它似乎有一个名为“侦听器”附加到MenuItem(我可以看到这个时,静态调试一个监听器MenuItem设置)。任何想法如何正确添加侦听器?

回答

3

他们需要被创建并添加如下(从one of my previous answers复制):

FacesContext context = FacesContext.getCurrentInstance(); 
MethodExpression actionListener = context.getApplication().getExpressionFactory() 
    .createMethodExpression(context.getELContext(), "#{bean.actionListener}", null, new Class[] {ActionEvent.class}); 
uiCommandComponent.addActionListener(new MethodExpressionActionListener(actionListener)); 

...其中#{bean.actionListener}确实存在,并宣布与托管bean名称bean相关的支撑类似如下:

public void actionListener(ActionEvent event) { 
    // ... 
} 

更多importantingly,你需要给任何动态创建UICommand(和UIInput )组件也是一个固定的ID,否则它会得到一个自动生成的ID,这可能导致JSF无法在应用请求值阶段定位/关联它。

因此,也这样做:

uiCommandComponent.setId("someFixedId"); 
+0

然后你apprarently仍然使用旧JSF 1.0/1.1(已超过换成1.2 4(!!)年前),点击上述链接看看JSF 1.1创建一个ActionListener的方法,你仍然需要自己设置一个固定的ID – BalusC

+0

事实证明在Maven中有一个引用到另一个使用MyFaces的项目,即使我有JSF 1.2它没有编译: - )...再次感谢您的回复。 –

+0

每个组件的唯一ID。如有必要,您可以添加一些计数器,例如'child.setId(“someFixedId”+ parent.getChildCount()); parent.getChildren()。add(child);' – BalusC

0

的主要问题,通过BalusC指出的是,你需要设置ID。 然后,您可以添加事件侦听器,如下所示: private MenuItem createItem(String name){ MenuItem item = new MenuItem(); item.addActionListener(新的ActionListener(){

 public void processAction(ActionEvent event) 
       throws AbortProcessingException { 
      // handle event 

     } 
    }); 
    item.setValue(name); 
    return item; 
}