javafxtreetableviewjfoenix

Fitting an ImageView into a TreeTableCell


I am using a JFXTreeTableView which has a column which displays images. The column is constucted like this:

JFXTreeTableColumn<MyLog, ImageView> statusColumn = new JFXTreeTableColumn<>("Status");
statusColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<MyLog, ImageView> param) -> {
    return param.getValue().getValue().statusImage;
});

The class MyLog looks like this:

public class MyLog extends RecursiveTreeObject<MyLog> {


    // more properties...
    public ObjectProperty<ImageView> statusImage = new SimpleObjectProperty<ImageView>();

    public MyLog(String imagePath)
    {
        statusImage.set(new ImageView(new Image(MyProject.class.getResourceAsStream(imagePath))));
    }
}

The image I am trying to display is this one:

enter image description here

However, the image is not fitting into the cell correctly. This is how the table looks:

enter image description here

How can I make the image fit into the cell without modifing the image itself?


Solution

  • You should seperate the data you want to display (Image) and the way it's displayed (ImageView).

    This is done by modifying MyLog's statusImage property to contain type Image and using a cellFactory that returns TreeTableCells that use ImageViews to display the images.

    public class MyLog extends RecursiveTreeObject<MyLog> {
    
        // more properties...
    
        public final ObjectProperty<Image> statusImage;
    
        public MyLog(String imagePath) {
            this(new Image(MyProject.class.getResourceAsStream(imagePath)));
        }
    
        /**
         * Constructor for passing Image objects.
         * (Could be helpful to reuse Images to reduce the footprint.)
         */
        public MyLog(Image statusImage) {
            this.statusImage = new SimpleObjectProperty(statusImage);
        }
    
    }
    
    statusColumn.setCellFactory(column -> new JFXTreeTableCell<MyLog, Image>() {
    
        private final ImageView imageView;
    
        {
            imageView = new ImageView();
            imageView.setFitWidth(20);
            imageView.setFitHeight(20);
            setGraphic(imageView);
        }
    
        @Override
        protected void updateItem(Image item, boolean empty) {
            super.updateItem(item, empty);
            imageView.setImage(item);
        }
    });