我正在按照此处给出的示例进行操作。我必须为员工列表显示 CheckBox 和 RadioButton,用户可以在其中选择许多 CheckBox,但只能选择一个 RadioButton。只是正常的行为。我首先从 Radiobutton 开始,运行后我的所有单选按钮都会自动选择。
我有以下 index.xhtml 页面
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<f:event listener="#{userPreferenceBean.preRender}" type="preRenderView" />
<h:head>
<title>Datatable with Checkbox and RadioButton Example</title>
</h:head>
<h:body>
<h:form>
<p:dataTable id="employeeDataTable" var="employee" value="#{userPreferenceBean.employeeList}"
rowKey="#{userPreferenceBean.employeeDataModel}" paginator="true" rows="10"
selection="#{userPreferenceBean.selectedEmployeeList}">
<f:facet name="header">
Showing employee List
</f:facet>
<p:column selectionMode="single" style="width:2%"></p:column>
<p:column headerText="Name" style="width:48%">
#{employee.name}
</p:column>
<p:column headerText="Department" style="width:48%">
#{employee.department}
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
我的支持 bean 是:
@ManagedBean
@SessionScoped
public class UserPreferenceBean implements Serializable{
private static final long serialVersionUID = 1L;
private List<Employee> employeeList;
private List<Employee> selectedEmployeeList;
private EmployeeDataModel employeeDataModel;
public void preRender(ComponentSystemEvent ebent){
System.out.println("Inside prerender");
}
@PostConstruct
public void initializeEmployeeList(){
createEmployeeList();
employeeDataModel = new EmployeeDataModel(employeeList);
}
private void createEmployeeList(){
employeeList = new ArrayList<>();
employeeList.add(new Employee("Sudipta",29,"Computer"));
employeeList.add(new Employee("Bunty", 29, "Electrical"));
employeeList.add(new Employee("Pradipta", 24, "Computer"));
}
//Other Getter and Setters
以下是 POJO 员工类别:
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
private String department;
//Constructor and Getters+Setters
这是我的 DataModel 类:
public class EmployeeDataModel extends ListDataModel<Employee> implements SelectableDataModel<Employee>{
public EmployeeDataModel(){
}
public EmployeeDataModel(List<Employee> employees){
super(employees);
}
@Override
public Employee getRowData(String rowKey) {
@SuppressWarnings("unchecked")
List<Employee> employees = (List<Employee>) getWrappedData();
for(Employee employee : employees){
if(employee.getName().equals(rowKey))
return employee;
}
return null;
}
@Override
public Object getRowKey(Employee employee) {
return employee.getName();
}
}
您知道为什么所有单选按钮都会自动被选中以及我需要做哪些更改吗?谢谢。附上截图