1

My TableView is populated with data from a list of objects. The first column is a Boolean value.

Instead of displaying True or False in the cell, I would like to display an image if True and leave the cell empty if it's False.

This is how I populate the TableView:

colStarred.setCellValueFactory(new PropertyValueFactory<>("starred"));
colDate.setCellValueFactory(new PropertyValueFactory<>("date"));
colTime.setCellValueFactory(new PropertyValueFactory<>("time"));

I know that I need to use a custom TableCell and a CellValueFactory but I'm having a hard time wrapping my head around the documentation (I have not used Java factories in the past).

My research has lead to several answers regarding similar situations, but they all seem to deal with just displaying an image in the cell. I have been unable to find a solution for checking a boolean to determine whether an image should be displayed or not.

How do I check the starredProperty of my objects and show an image if it is True?

Thank you for all the help everyone has provided me in the past!

Zephyr
  • 9,885
  • 4
  • 28
  • 63

1 Answers1

2

I'll assume the column to be a TableColumn<MyItemClass, Boolean>.

You simply create TableCells that adjust their look according to the item that gets passed to the updateItem method.

In this case we'll use a ImageView as graphic of the cell.

The following images are displayed depending on the item of the cell:

  • no image if the cell is empty or contains null
  • imageTrue if the item is true
  • imageFalse otherwise

You may of course use imageFalse = null for an empty cell when the item is false.

final Image imageTrue = ...
final Image imageFalse = ...

// set cellfactory
colStarred.setCellFactory(col -> new TableCell<MyItemClass, Boolean>() {

    private final ImageView imageView = new ImageView();

    {
        // initialize ImageView + set as graphic
        imageView.setFitWidth(20);
        imageView.setFitHeight(20);
        setGraphic(imageView);
    }

    @Override
    protected void updateItem(Boolean item, boolean empty) {
        if (empty || item == null) {
            // no image for empty cells
            imageView.setImage(null);
        } else {
            // set image for non-empty cell
            imageView.setImage(item ? imageTrue : imageFalse);
        }
    }

});

What happens when the program is displayed is this:

  • The TableView creates cells needed to display the items using the cellfactories.
  • The TableView assigns the items to the cells. These items may be changed multiple times. Cells may also become empty after being filled. When this happens the updateItem methods of the TableCells are called.
fabian
  • 80,457
  • 12
  • 86
  • 114
  • This worked beautifully. And thank you for explaining what is actually happening behind the scenes. I do understand a bit more now! – Zephyr Jun 28 '17 at 16:31