我正在动态创建一个 MenuItem,并且我想在单击 MenuItem 时添加一个自定义侦听器。
我已经尝试添加 addActionListener 和 setActionListener ,但是当点击链接时这些都不会被调用。
似乎有一个名为“listeners”的列表附加到 MenuItem(我可以在使用侦听器静态调试 MenuItem 设置时看到这一点)。知道如何正确添加侦听器吗?
它们需要按如下方式创建和添加(从我以前的答案之一复制):
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 类中声明如下bean
:
public void actionListener(ActionEvent event) {
// ...
}
更重要的是,您还需要为任何动态创建 UICommand
的(和UIInput
)组件提供一个固定 ID,否则它将获得一个自动生成的 ID,这可能导致 JSF 在应用请求值阶段无法定位/关联它。
因此,也这样做:
uiCommandComponent.setId("someFixedId");
BalusC 指出的主要问题是您需要设置 ID。然后您可以按如下方式添加事件侦听器: private MenuItem createItem(String name){ MenuItem item=new MenuItem(); item.addActionListener(new ActionListener() {
public void processAction(ActionEvent event)
throws AbortProcessingException {
// handle event
}
});
item.setValue(name);
return item;
}