在JavaFX中的所有表格单元格上设置工具提示 [英] Setting a tooltip on all table cells in JavaFX

查看:148
本文介绍了在JavaFX中的所有表格单元格上设置工具提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序包含 TableView 。根据每行中特定单元格的值,通过为此列设置具有 setCellFactory 的自定义单元格工厂来更改行样式。这很好。

My application contains a TableView. Depending on the value of a specific cell in each row, the row style is changed by setting a custom cell factory with setCellFactory for this column. This works fine.

现在我想添加一个工具提示,使用 setTooltip()这没什么大不了的。但是,此工具提示应设置为表中的每个单元格,而不仅仅是为其指定的列。我该如何实现呢?

Now I'd like to add a tooltip which is no big deal using setTooltip(). However this tooltip shall be set for every cell in the table, not just the column it is specified for. How can I implement this?

推荐答案

一旦设置了表(即创建和添加列,以及单元工厂在所有列上设置),您可以装饰列的单元工厂:

Once the table is set up (i.e. the columns are created and added, and the cell factories are set on all the columns), you can "decorate" the columns' cell factories:

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 的任何类型,即这假设您

Here just replace TableDataType with whatever type you used to declare your TableView, i.e. this assumes you have

TableView<TableDataType> table ;

现在,之后创建了列,将它们添加到表中,并设置所有的单元工厂,你只需要:

Now, after you have created the columns, added them to the table, and set all their cell factories, you just need:

for (TableColumn<TableDataType, ?> column : table.getColumns()) {
    addTooltipToColumnCells(column);
}

或者如果您更喜欢Java 8方式:

or if you prefer a "Java 8" way:

table.getColumns().forEach(this::addTooltipToColumnCells);

这篇关于在JavaFX中的所有表格单元格上设置工具提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆