我在JavaFX 8中编写代码,并设置了一个ObservableList " consulting ">
private ObservableList<Consultation> queue_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(""));
}
};
}
});
}
我编写了上面的代码,以便在"Consultation"的opened_by_userProperty()时,整行将以粉红色突出显示。对象为真。
我的问题是,当行数减少(因为列表不断从数据库更新)而最后一行突出显示时。即使该行变为空,该行也将保持高亮显示。当突出显示的行变为空时,将没有opened_by_userProperty()要绑定,并且上面的代码不做任何事情来恢复默认背景色。
我正在考虑添加一个else语句:
if (!empty) {
styleProperty().bind(Bindings.when(row1.opened_by_userProperty())
.then("-fx-background-color: pink;")
.otherwise(""));
} else {
// some code to restore default background color
}
我不知道如何设置背景色默认时,行是空的。有什么建议吗?非常感谢。
正如您所观察到的,您需要处理updateItem()
方法中行为空的情况。否则,当一行从非空变为空时,它的样式将不会被重置。
if (!empty) {
styleProperty().bind(Bindings.when(row1.opened_by_userProperty())
.then("-fx-background-color: pink;")
.otherwise(""));
} else {
styleProperty().unbind();
setStyle("");
}
应该做你想做的。
一般来说,任何自定义单元格的updateItem()
方法应该始终处理所有可能的场景,包括空单元格。