2012-10-16 66 views
2

我需要實現一個動態menumodel。在actionlistener中,我需要調用一個支持bean的方法。當我將actionListener添加到menuItem時,我得到一個java.lang.InstantiationException。如何在Primefaces中爲MenuItem調用ActionListener

@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); 
    } 
+0

儘量讓'MenuActionListener'正常類,而不是內部,HTTP ://www.javabeat.net/2007/11/event-driven-programming-with-jsf/ – Daniel

+0

我可以,但我想從內部類執行一個bean方法「測試」。我不能那樣做嗎? – Smith

+0

從未嘗試過.... – Daniel

回答

相關問題