我如何知道TableView中的项目是否被截断(省略号)?

时间:2018-09-13 21:19:39

标签: javafx javafx-8

我正在使用TableView。它需要显示的String数据具有可变的长度。我怎么知道String数据是否太长(从而出现省略号)?

我的猜测是使用自定义TableCell(调用setCellFactory()),在updateItem()中,我应该查询数据的像素宽度,但是我不知道如何。

        column.setCellFactory(column ->
            new TableCell<Transaction, String>() {
                @Override
                protected void updateItem(final String item, final boolean empty) {
                    super.updateItem(item, empty);
                    setText(item);


                    if (/*measuredWidth > getWidth()*/) {
                        setTooltip(new Tooltip(item));
                    }
                }
            }
    );

对此有何想法?

1 个答案:

答案 0 :(得分:0)

column.setCellFactory(col -> new TableCell<Object, String>()
    {
        @Override
        protected void updateItem(final String item, final boolean empty)
        {
            super.updateItem(item, empty);
            setText(item);
            TableColumn tableCol = (TableColumn) col;

            if (item != null && tableCol.getWidth() < new Text(item + "  ").getLayoutBounds().getWidth())
            {
                tooltipProperty().bind(Bindings.when(Bindings.or(emptyProperty(), itemProperty().isNull())).then((Tooltip) null).otherwise(new Tooltip(item)));
            } else
            {
                tooltipProperty().bind(Bindings.when(Bindings.or(emptyProperty(), itemProperty().isNull())).then((Tooltip) null).otherwise((Tooltip) null));
            }

        }
    });