2012-10-03 32 views
2

在JavaFX中,如何获取给定TableColumn的给定单元格的单元格渲染器实例?JavaFX:TableColumn的给定行的单元格渲染器实例

在Swing,做它的方式是调用getTableCellRendererComponent()的TableCellRenderer该列,并通过它的行和列索引。但JavaFX似乎非常不同。我试着搜索并通过TableColumn API,但我似乎无法弄清楚这一点。也许我必须做点什么getCellFactory()

我的目标是查询列的每个单元格渲染器的首选宽度,然后计算在该列上设置的宽度,以便该列的所有单元格的内容都完全可见。

这里问了一个问题 - JavaFX 2 Automatic Column Width - 其中原始海报的目标与我的相同。但还没有一个令人满意的答案。

回答

0

TableColumnHeader类中有resizeToFit()方法。不幸的是它受到保护。如何只将代码复制粘贴到您的应用程序,并改变了一点:

protected void resizeToFit(TableColumn col, int maxRows) { 
    List<?> items = tblView.getItems(); 
    if (items == null || items.isEmpty()) return; 

    Callback cellFactory = col.getCellFactory(); 
    if (cellFactory == null) return; 

    TableCell cell = (TableCell) cellFactory.call(col); 
    if (cell == null) return; 

    // set this property to tell the TableCell we want to know its actual 
    // preferred width, not the width of the associated TableColumn 
    cell.getProperties().put("deferToParentPrefWidth", Boolean.TRUE);//the change is here, only the first parameter, since the original constant is not accessible outside package 

    // determine cell padding 
    double padding = 10; 
    Node n = cell.getSkin() == null ? null : cell.getSkin().getNode(); 
    if (n instanceof Region) { 
     Region r = (Region) n; 
     padding = r.getInsets().getLeft() + r.getInsets().getRight(); 
    } 

    int rows = maxRows == -1 ? items.size() : Math.min(items.size(), maxRows); 
    double maxWidth = 0; 
    for (int row = 0; row < rows; row++) { 
     cell.updateTableColumn(col); 
     cell.updateTableView(tblView); 
     cell.updateIndex(row); 

     if ((cell.getText() != null && !cell.getText().isEmpty()) || cell.getGraphic() != null) { 
      getChildren().add(cell); 
      cell.impl_processCSS(false); 
      maxWidth = Math.max(maxWidth, cell.prefWidth(-1)); 
      getChildren().remove(cell); 
     } 
    } 

    col.impl_setWidth(maxWidth + padding); 
} 

然后就可以调用加载数据后的方法:

for (TableColumn clm : tblView.getColumns()) { 
    resizeToFit(clm, -1); 
}