Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get row value inside updateItem() of CellFactory

Tags:

java

javafx

ageColumn.setCellFactory(param -> new TableCell<Person, String>(){
    @Override
    protected void updateItem(String item, boolean empty) {
        param.getCellFactory().
        super.updateItem(item, empty);
        setText(empty ? null : String.valueOf(item));

        if(person.getName.equals("MATEUS")) {
            setStyle("-fx-background-color: red;");
        }
    }
});

How to get this "Person" which is the row value from the Table? I can only get the value from the cell, but not the entire object.

like image 470
Mateus Viccari Avatar asked Oct 28 '15 13:10

Mateus Viccari


1 Answers

You can do

Person person = getTableView().getItems().get(getIndex());

You can also do

Person person = (Person) getTableRow().getItem();

but this is less desirable (in my opinion) because getTableRow() returns a raw type, and consequently it requires the unchecked downcast.

Obviously either of these only works if empty is false, so they should be inside a check for that:

ageColumn.setCellFactory(param -> new TableCell<Person, String>(){
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
            setStyle("");
        } else {
            setText(item);
            Person person = getTableView().getItems().get(getIndex());
            if(person.getName.equals("MATEUS")) {
                setStyle("-fx-background-color: red;");
            } else {
                setStyle("");
            }
        }
    }
});
like image 93
James_D Avatar answered Nov 14 '22 22:11

James_D