简体   繁体   English

在JSF中动态添加组件?

[英]Dynamically add the component in JSF?

In my application the component has to change dynamically. 在我的应用程序中,组件必须动态更改。 I am having a Datatable in that i am having two column, first is a <h:selectoneMenu> in the menu i am having two data(the data are 1 and 2) if 1 is selected then a <h:inputText> should appear and if 2 is selected <h:selectoneMenu> should appear. 我有一个数据表,因为我有两列,首先是菜单中的<h:selectoneMenu>我有两个数据(数据分别为1和2),如果选择了1,则应出现<h:inputText>如果选择了2,应显示<h:selectoneMenu> Need help to do this? 需要帮助吗?

My JSF 我的JSF

   <h:selectOneMenu id="menu" value="#{sample.data}" rendered="true" valueChangeListener="#{sample.change}">
    <f:selectItem itemLabel="Data" itemValue=""/>
    <f:selectItems value="#{sample.list1}"/>
            <a4j:support event="onchange" reRender="text" />
</h:selectOneMenu>
<h:inputText id="text" value="#{sample.input}" rendered="#{sample.status}" />

My Manged Bean Class 我的豆类

public class Sample {
private Boolean status;          //Getter & Setter
private List<SelectItem> list1;  //Setter
private String input;            //Getter & Setter
private String data;             //Getter & Setter

public void change(ValueChangeEvent event){
System.out.println((String)event.getNewValue());
if(((String)event.getNewValue()).equals("value1")){
    status=true;
}
else if(((String)event.getNewValue()).equals("value2")){
    status=false;
}
}
public Boolean getStatus(){
if(status==null){
    status=true;
}
return status;
}
public List<SelectItem> getList1() {
if(list1==null) {
list1 = new ArrayList<SelectItem>();
list1.add(new SelectItem("value1", "label1"));
list1.add(new SelectItem("value2", "label2"));
}
return list1;
}
}

My advice would be: do not add/remove component dynamically. 我的建议是:不要动态添加/删除组件。 Solve your problem another way: 用另一种方法解决您的问题:

  • Toggle visibility of components 切换组件的可见性
  • Rebind the data belonging to a component 重新绑定属于组件的数据

Adding/removing component dynamically is always a source of trouble and chances are that you can do it another way much simpler. 动态添加/删除组件始终是麻烦的源头,而且您有可能以另一种简单得多的方式执行此操作。

In your case, playing with the visibility using rendered attribute should be enough. 在您的情况下,使用rendered属性来rendered可见性就足够了。

Let's say you have something like this 假设您有这样的事情

<h:selectoneMenu id="selectOne" rendered="#{myBean.selectOneRendered}">
<h:inputText id="input" rendered="#{!myBean.selectOneRendered}">

You have both the components in your jsp page. 您在jsp页面中同时拥有这两个组件。 Once you reload the jsp the rendered prorpertie will be checked. 重新加载jsp后,将检查渲染的属性。

in your myBean you must to have something like this 在您的myBean中,您必须具有这样的内容

public boolean isSelectOneRendered(){
 boolean rendered;
 //Do something here
 return rendered;
}

if the result is true then the selectOne will be rendered and the input will not and the other way round. 如果结果为true,则将呈现selectOne,而不会呈现输入,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM