You can use <p:tabView>
to show a dynamic tabset based on some collection of beans. You can present the "Add" tab as the last tab of the tabset. You can if necessary even style it differently. You can use <p:ajax event="tabChange">
to hook a tab change listener wherein you can check if the "Add" tab has been opened and then add the new tab.
E.g.
<h:form id="form">
<p:tabView id="tabs" value="#{bean.tabs}" var="tab" widgetVar="w_tabs">
<p:ajax event="tabChange" listener="#{bean.changeTab}" oncomplete="if (args.newTabIndex) w_tabs.select(args.newTabIndex)" />
<p:tab title="#{tab.title}">
<p>#{tab.content}</p>
</p:tab>
</p:tabView>
</h:form>
with
@ManagedBean
@ViewScoped
public class Bean implements Serializable {
private List<Tab> tabs;
@PostConstruct
public void init() {
// Just a stub. Do your thing to populate tabs.
// Make sure that the last tab is the "Add" tab.
tabs = new ArrayList<Tab>();
tabs.add(new Tab("tab1", "content1"));
tabs.add(new Tab("tab2", "content2"));
tabs.add(new Tab("Add...", null));
}
public void changeTab(TabChangeEvent event) {
int currentTabIndex = ((TabView) event.getComponent()).getActiveIndex();
int lastTabIndex = tabs.size() - 1; // The "Add" tab.
if (currentTabIndex == lastTabIndex) {
tabs.add(lastTabIndex, new Tab("tab" + tabs.size(), "content" + tabs.size())); // Just a stub. Do your thing to add a new tab.
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.update("form:tabs"); // Update the p:tabView to show new tab.
requestContext.addCallbackParam("newTabIndex", lastTabIndex); // Triggers the oncomplete.
}
}
public List<Tab> getTabs() {
return tabs;
}
}
The Tab
class is in this example just a plain javabean with properties title
and content
. The oncomplete
in <p:ajax>
is necessary because the tab content would otherwise disappear after adding the new tab (which look much like a PF bug, after all; I was using 3.3 by the way).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…