我正在使用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));
}
}
}
);
对此有何想法?
答案 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));
}
}
});