JavaFx:在表格单元格中显示一个图标



我指定了以下表格列单元格:

public class TableCellWithImage<T> extends TableCell<T, String> {
private final ImageView image;
public TableCellWithImage() {
// add ImageView as graphic to display it in addition
// to the text in the cell
image = new ImageView( new Image( getClass().getResourceAsStream("/eyes.png")));
image.setFitWidth(24);
image.setFitHeight(24);
image.setPreserveRatio(true);
setGraphic(image);
setMinHeight(70);
}
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
// set back to look of empty cell
setText(null);
setGraphic(null);
} else {
setText(item);
setGraphic(image);
}
}
}

为了应用它,我使用

content_column_.setCellFactory(new Callback<TableColumn<DbEntry, String>, TableCell<DbEntry, String>>() {
@Override
public TableCell<DbEntry, String> call(TableColumn<DbEntry, String> param) {
return new TableCellWithImage<>();
}
});

如何在单元格内对齐图形图像和文本?我想要一个图像放在右角,并且只有在鼠标悬停的情况下才可见。

这里是制作技巧的最终解决方案。

public class TableCellWithImage<T> extends TableCell<T, String> {
private final ImageView image;
BooleanProperty is_image_visible_ = new SimpleBooleanProperty( false );
public TableCellWithImage() {
// add ImageView as graphic to display it in addition
// to the text in the cell
image = new ImageView( new Image( getClass().getResourceAsStream("/eyes.png")));
image.setFitWidth(24);
image.setFitHeight(24);
image.setPreserveRatio(true);
setGraphic(image);
setMinHeight(70);
setGraphicTextGap(10);
setContentDisplay(ContentDisplay.RIGHT);
setOnMouseEntered(mouseEvent -> {
is_image_visible_.set(true);
});
setOnMouseExited(mouseEvent -> {
is_image_visible_.set(false);
});
image.visibleProperty().bind(is_image_visible_);
}
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
// set back to look of empty cell
setText(null);
setGraphic(null);
} else {
setText(item);
setGraphic(image);
}
}
}

最新更新