How to invoke ActionListener for MenuItem in primefaces

被刻印的时光 ゝ 提交于 2019-12-12 21:04:40

问题


I need to implement a dynamic menumodel. In the actionlistener, i need to call a backing bean method. When I add the actionListener to the menuItem I am getting an 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); 
}

I have also tried using MethodExpressionActionListener. In this case the parameter passed "item1" is alays null. Please let me know on how I could pass a parameter in a 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);
    }  

回答1:


Try to make the MenuActionListener a normal class instead of inner class

Also take a look at this Event Driven Programming with JSF



来源:https://stackoverflow.com/questions/12922535/how-to-invoke-actionlistener-for-menuitem-in-primefaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!