Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX Table Cell Formatting

    TableColumn<Event,Date> releaseTime  = new TableColumn<>("Release Time");
    releaseTime.setCellValueFactory(
                new PropertyValueFactory<Event,Date>("releaseTime")
            );

How can I change the format of releaseTime? At the moment it calls a simple toString on the Date object.

like image 913
DD. Avatar asked Jul 10 '12 11:07

DD.


People also ask

What is TableView in JavaFX?

The TableView class provides built-in capabilities to sort data in columns. Users can alter the order of data by clicking column headers. The first click enables the ascending sorting order, the second click enables descending sorting order, and the third click disables sorting. By default, no sorting is applied.

How to sort TableView in JavaFX?

The JavaFX TableView enables you to sort the rows in the TableView. There are two ways rows can be sorted. The first way is for the user to click on the TableColumn header cell (where the column title is displayed). This will sort the rows in the TableView after the values of that column.

What is a Cell factory Java?

Cell Value Factory : it is like a "toString()" of only part of the row item for that related cell. Cell Factory : it is a renderer of the cell from the cell item. Default behavior is setText(cell. item. toString()) if the cell item is not a Node , setGraphic((Node)cell.


1 Answers

I'd recommend using Java generics to create re-usable column formatter that takes any java.text.Format. This cuts down on the amount of boilerplate code...

private class ColumnFormatter<S, T> implements Callback<TableColumn<S, T>, TableCell<S, T>> {
    private Format format;

    public ColumnFormatter(Format format) {
        super();
        this.format = format;
    }
    @Override
    public TableCell<S, T> call(TableColumn<S, T> arg0) {
        return new TableCell<S, T>() {
            @Override
            protected void updateItem(T item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setGraphic(null);
                } else {
                    setGraphic(new Label(format.format(item)));
                }
            }
        };
    }
}

Examples of usage

birthday.setCellFactory(new ColumnFormatter<Person, Date>(new SimpleDateFormat("dd MMM YYYY")));
amplitude.setCellFactory(new ColumnFormatter<Levels, Double>(new DecimalFormat("0.0dB")));
like image 86
Adam Avatar answered Nov 25 '22 08:11

Adam