→ UPDATED VERSION of this article available at: JavaFX 8 TableView Cell Renderer

In this post I will show how to customize the rendering of a JavaFX 2 TableView. The Birthday column in the screenshot below is a formatted Calendar object. Depending on the year, the text color is changed.

TableView Cell Renderer


How a Table Cell is Rendered

Each table cell will receive an object, in our case it is an instance of Person. To do the rendering, the cell will need a Cell Value Factory and a Cell Factory:

Cell Value Factory

The cell must know which part of Person it needs to display. For all cells in the birthday column this will be the Persons birthday value.

This is our birthday column:

private TableColumn<Person, Calendar> birthdayColumn;

And later during initialization, we’ll set the Cell Value Factory:

birthdayColumn.setCellValueFactory(
    new PropertyValueFactory<Person, Calendar>("birthday"));

So far nothing too fancy.

Cell Factory

Once the cell has the value, it must know how to display that value. In our case, the birthday’s Calendar value must be formatted and colored depending on the year.

birthdayColumn.setCellFactory(new Callback<TableColumn<Person, Calendar>, TableCell<Person, Calendar>>() {
	@Override
	public TableCell<Person, Calendar> call(TableColumn<Person, Calendar> param) {
		return new TableCell<Person, Calendar>() {
    
			@Override
			protected void updateItem(Calendar item, boolean empty) {
				super.updateItem(item, empty);
        
              if (!empty) {
                // Use a SimpleDateFormat or similar in the format method
                setText(format(item));
                
                if (item.get(Calendar.YEAR) == 2011) {
                  setTextFill(Color.CHOCOLATE);
                } else {
                  setTextFill(Color.BLACK);
                }
                
              } else {
                setText(null);
              }
			}
		};
	}
});

The Cell Factory contains some complicated stuff (Callback, Generics and Anonymous Inner Classes). Don’t worry too much about all this. Just focus on the important part which is the updateItem(...) method.

This updateItem(...) method gets called whenever the cell should be rendered. We receive the Calendar item that must be rendered. If empty is true we don’t do anything. Otherwise we format the item and set the text of the cell. Depending on the year, we also set the text color.


ListView and TreeView

Note that the JavaFX 2 ListView and TreeView are rendered in a very similar way.


Download

Download the complete tableview-cell-renderer example.