Primefaces 5.0中有一个DataGrid组件。它显示按行分割的输入数据。如何显示按列分割的数据?
A B C A D G
D E F --> B E H
G H C F
我的解决方案是在Primefaces的DataGrid组件中置换数据是覆盖DataGridRenderer
类的encodeTable()
方法。
@Override
protected void encodeTable(FacesContext context, DataGrid grid) throws IOException {
ResponseWriter writer = context.getResponseWriter();
int columns = grid.getColumns();
int firstRowIndex = grid.getFirst();
int rowIndex = firstRowIndex;
int rows = grid.getRows();
int itemsToRender = rows != 0 ? rows : grid.getRowCount();
int numberOfRowsToRender = (itemsToRender + columns - 1) / columns;
String transpose = (String) grid.getAttributes().get("transpose");
boolean isTranspose = transpose != null ? Boolean.valueOf(transpose) : false;
writer.startElement("table", grid);
writer.writeAttribute("class", DataGrid.TABLE_CLASS, null);
writer.startElement("tbody", null);
for (int i = 0; i < numberOfRowsToRender; i++) {
writer.startElement("tr", null);
writer.writeAttribute("class", DataGrid.TABLE_ROW_CLASS, null);
for (int j = 0; j < columns; j++) {
writer.startElement("td", null);
writer.writeAttribute("class", DataGrid.TABLE_COLUMN_CLASS, null);
if (isTranspose) {
writer.writeAttribute("style", String.format("width: %d%%;", 100 / columns), null);
}
grid.setRowIndex(isTranspose ? numberOfRowsToRender * j + i + firstRowIndex : rowIndex);
if (grid.isRowAvailable()) {
renderChildren(context, grid);
}
rowIndex++;
writer.endElement("td");
}
writer.endElement("tr");
}
grid.setRowIndex(-1); //cleanup
writer.endElement("tbody");
writer.endElement("table");
}
并在faces-config.xml
:
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.DataGridRenderer</renderer-type>
<renderer-class>org.primefaces.component.datagrid.TransposableDataGridRenderer</renderer-class>
</renderer>
</render-kit>
现在我可以为<p:dataGrid>
标签指定transposable="true"
属性。代码还"修复"样式表,使每个页面具有相同数量的列,即使在最后一页上没有足够的数据来覆盖所有列。