Reputation: 51
I'm writing codes in JavaFX 8 and set up an ObservableList of "Consultation" objects which constantly updates by querying a MySQL database.
private ObservableList<Consultation> queue_list;
and made a table showing the list
@FXML
public TableView<Consultation> table_queue;
@FXML
void initialize() throws SQLException {
queue_list = FXCollections.observableArrayList();
queue_list = dbConnection.listConsultations();
col_1.setCellValueFactory(new PropertyValueFactory<>("1"));
col_2.setCellValueFactory(new PropertyValueFactory<>("2"));
col_3.setCellValueFactory(new PropertyValueFactory<>("3"));
table_queue.setItems(queue_list);
table_queue.setRowFactory(new Callback<TableView<Consultation>, TableRow<Consultation>>() {
@Override
public TableRow<Consultation> call(TableView<Consultation> param) {
return new TableRow<Consultation>() {
@Override
protected void updateItem(Consultation row1, boolean empty) {
super.updateItem(row1, empty);
if (!empty)
styleProperty().bind(Bindings.when(row1.opened_by_userProperty())
.then("-fx-background-color: pink;")
.otherwise(""));
}
};
}
});
}
I wrote the above codes so that the whole row will be highlighted in pink when opened_by_userProperty() of the "Consultation" object is true.
My problem is, when the number of rows reduces (because the list is constantly updating from the database) while the last row is highlighted. That row will remain highlighted even if that row become empty. When a highlighted row become empty, there will be no opened_by_userProperty() to bind and the above code do nothing to restore the default background color.
I'm thinking about adding an else statement:
if (!empty) {
styleProperty().bind(Bindings.when(row1.opened_by_userProperty())
.then("-fx-background-color: pink;")
.otherwise(""));
} else {
// some code to restore default background color
}
I don't know how to set the background color to default when the row is empty. Is there any suggestion? Thanks a lot.
Upvotes: 0
Views: 140
Reputation: 209339
As you've observed, you need to deal with the case where the row is empty in the updateItem()
method. Otherwise when a row goes from being non-empty to empty, it's style will not be reset.
if (!empty) {
styleProperty().bind(Bindings.when(row1.opened_by_userProperty())
.then("-fx-background-color: pink;")
.otherwise(""));
} else {
styleProperty().unbind();
setStyle("");
}
should do what you want.
In general, the updateItem()
method for any custom cell should always handle all possible scenarios, including empty cells.
Upvotes: 1