首页 > 解决方案 > 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<>();
    }
});

如何对齐单元格内的图形图像和文本?我希望将图像放置在右上角,并且仅在鼠标悬停时可见。

标签: javafx

解决方案


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

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);
        }
    }
}

推荐阅读