I am trying to create a dynamic menu: a menu like those found on Amazon or eBay to browse categories. My first attempt is shown below:
The backing bean:
@ManagedBean
@ViewScoped
public class CategoryBackBean implements ActionListener {
private MenuModel model;
private Category category;
public CategoryBackBean() throws IOException {
category = Category.createRootCategory();
createModel();
}
private void createModel() throws IOException {
MenuModel tempModel = new DefaultMenuModel();
for(Category c : category.getChildCategories()) {
MenuItem childItem = new MenuItem();
childItem.setValue(c.getName());
childItem.addActionListener(this);
tempModel.addMenuItem(childItem);
}
this.model = tempModel;
}
public MenuModel getModel() {
return model;
}
@Override
public void processAction(ActionEvent event) throws AbortProcessingException {
try {
MenuItem item = (MenuItem) event.getSource();
String categoryName = (String) item.getValue();
for(Category c : category.getChildCategories()) {
if(c.getName().equals(categoryName)) {
category = c;
createModel();
return;
}
}
} catch (IOException ex) {
Logger.getLogger(CategoryBackBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The webpage:
<h:body>
<h:form>
<p:menubar model="#{categoryBackBean.model}" />
</h:form>
</h:body>
For starters, my design doesn't work: the initial menu is created, but when clicking on buttons, the menu is not recreated in sub-categories.
What is the best way to tackle this general problem? I'm not looking for quick hacks to get the above code working- I'm looking for a general design for a recursive menu.