Set tooltips on all table cells in JavaFX
My application contains a tableview Change the row style by setting a custom cell factory with setcellfactory for this column based on the value of a specific cell in each row It works well
Now I want to add a tooltip. It's no big deal to use settooltip() However, you should set this tooltip for each cell in the table, not just the column specified for it How can I achieve it?
Solution
After setting up the table (that is, creating and adding columns and setting up cell factories on all columns), you can "decorate" the cell factories of the columns:
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 ; }); }
Here, simply replace the tabledatatype with any type you use to declare the tableview, that is, it is assumed that you have
TableView<TableDataType> table ;
Now, after creating the columns, adding them to the table, and setting up all the cell factories, you just need to:
for (TableColumn<TableDataType,?> column : table.getColumns()) { addTooltipToColumnCells(column); }
Or if you prefer the "Java 8" approach:
table.getColumns().forEach(this::addTooltipToColumnCells);