Milan Milan - 23 days ago 9
Java Question

Error Trying to get cell data value JavaFX TableView

I am trying to get the value of the current cell, I am mapping an array list to a single column.

Here is my code:

TableColumn<ObservableList<String>, String> nameColumn = new TableColumn<>("Name");
nameColumn.setCellValueFactory(cellData -> {
Integer rowIndex = cellData.getValue();
return new ReadOnlyStringWrapper(rangeArrayList.get(rowIndex));
});

tableView.getColumns().add(nameColumn);


Here is my error:

enter image description here

How would I be able to fix this error?

Answer

You cannot do this using a the cellValueFactory unless your item contains the row information, since there is no information about the row other than the value it contains in TableColumn.CellDataFeatures.

If you want to use the row number to retrieve the data, you can do this using a cellFactory, since the index is available to the TableCell:

public static <T> Callback<TableColumn<T, Void>, TableCell<T, Void>> cellFactory(final List<?> list) {
    return c -> new TableCell<T, Void>() {

        @Override
        public void updateIndex(int i) {
            super.updateIndex(i);
            setText(isEmpty() ? "" : Objects.toString(list.get(i), ""));
        }

    };
}
TableColumn<ObservableList<String>, Void> nameColumn = new TableColumn<>("Name");
nameColumn.setCellFactory(cellFactory(rangeArrayList));