我需要实现一个动态菜单模型。在 actionlistener 中,我需要调用一个支持 bean 方法。当我将 actionListener 添加到 menuItem 时,我得到一个 java.lang.InstantiationException。
@ManagedBean(name = "sampleBean")
@ViewScoped
public class Sample1 implements Serializable {
private MenuModel model;
public Sample1() {
model = new DefaultMenuModel();
for(int i = 0; i < 3; i++){
MenuItem item1 = new MenuItem();
item1.setValue("test1" + i);
item1.setAjax(false);
item1.setId("item1" + i);
item1.addActionListener(this.new MenuActionListener());
model.addMenuItem(item1);
}
}
// inner class action listener
class MenuActionListener implements ActionListener{
@Override
public void processAction(ActionEvent arg0) throws AbortProcessingException {
System.out.println("test... " + arg0.getComponent().getClientId());
test(arg0.getComponent().getClientId());
}
}
public void test(String test){
System.out.println("tested..." + test);
}
我也尝试过使用 MethodExpressionActionListener。在这种情况下,传递的参数“item1”为空。请让我知道如何在 methodExpression 中传递参数。
for(int i = 0; i < 3; i++){
MenuItem item1 = new MenuItem();
item1.setValue("test1" + i);
item1.setAjax(false);
item1.setId("item1" + i);
//item1.addActionListener(new MenuActionListener());
ExpressionFactory factory = FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
ELContext elContext = FacesContext.getCurrentInstance().getELContext();
MethodExpression expression = factory.createMethodExpression(elContext, "#{beanName.method(" + item1 + ")}", null, new Class[] {MenuItem.class});
item1.addActionListener(new MethodExpressionActionListener(expression));
model.addMenuItem(item1);
}