【发布时间】:2018-09-21 04:21:36
【问题描述】:
我的应用程序包含TableView。根据每行中特定单元格的值,通过为此列设置带有setCellFactory 的自定义单元格工厂来更改行样式。这很好用。
现在我想使用setTooltip() 添加一个没什么大不了的工具提示。但是,应该为表中的每个单元格设置此工具提示,而不仅仅是为其指定的列。我该如何实现?
【问题讨论】:
我的应用程序包含TableView。根据每行中特定单元格的值,通过为此列设置带有setCellFactory 的自定义单元格工厂来更改行样式。这很好用。
现在我想使用setTooltip() 添加一个没什么大不了的工具提示。但是,应该为表中的每个单元格设置此工具提示,而不仅仅是为其指定的列。我该如何实现?
【问题讨论】:
一旦设置好表格(即创建和添加列,并在所有列上设置单元工厂),您就可以“装饰”列的单元工厂:
private <T> void addTooltipToColumnCells(TableColumn<TableDataType,T> column) {
Callback<TableColumn<TableDataType, T>, TableCell<TableDataType,T>> existingCellFactory
= column.getCellFactory();
column.setCellFactory(c -> {
TableCell<TableDataType, T> cell = existingCellFactory.call(c);
Tooltip tooltip = new Tooltip();
// can use arbitrary binding here to make text depend on cell
// in any way you need:
tooltip.textProperty().bind(cell.itemProperty().asString());
cell.setTooltip(tooltip);
return cell ;
});
}
这里只需将TableDataType 替换为您用来声明TableView 的任何类型,即假设您有
TableView<TableDataType> table ;
现在,你已经创建了列,将它们添加到表中,并设置了它们的所有单元工厂,你只需要:
for (TableColumn<TableDataType, ?> column : table.getColumns()) {
addTooltipToColumnCells(column);
}
或者如果您更喜欢“Java 8”方式:
table.getColumns().forEach(this::addTooltipToColumnCells);
【讨论】:
tooltip 属性绑定到考虑单元格状态的绑定:cell.tooltipProperty().bind(Bindings.when(Bindings.or(cell.emptyProperty(), cell.itemProperty().isNull())).then((Tooltip) null).otherwise(tooltip));