在javaFX中更改特定的行颜色



这是我写的代码,用于更改皮革仪表处的行颜色<200,但在if条件下我面临空指针异常。首先,我从数据库中获取所有数据,并将它们全部添加到表视图中,这样就不会出现空指针异常。问题出在哪里?

@FXML
TableView<Leather> tableView;
ObservableList<Leather> data = FXCollections.observableArrayList();
@Override
public void initialize(URL location, ResourceBundle resources) {
tableView.setEditable(true);
codeCol.setCellValueFactory(new PropertyValueFactory<>("code"));
colorCol.setCellValueFactory(new PropertyValueFactory<>("color"));
meterCol.setCellValueFactory(new PropertyValueFactory<>("meter"));
indexCol.setCellFactory(col -> new TableCell<Task, String>() {
@Override
public void updateIndex(int index) {
super.updateIndex(index);
if (isEmpty() || index < 0) {
setText(null);
} else {
setText(Integer.toString(index+1));
}
}
});
data.addAll(storeService.getAll());
tableView.setItems(data);
tableView.setRowFactory(tv -> new TableRow<Leather>(){
@Override
protected void updateItem(Leather item, boolean empty) {
super.updateItem(item,empty);
if (item.getMeter()<200){
setStyle("-fx-background-color: #DB8A6B");
}
}
});
}

您需要在rowFactory中处理所有案例(与在cellFactory中相同(:

tableView.setRowFactory(tv -> new TableRow<Leather>(){
@Override
protected void updateItem(Leather item, boolean empty) {
super.updateItem(item,empty);
if (empty || item == null) {
setStyle("");
} else if (item.getMeter()<200){
setStyle("-fx-background-color: #DB8A6B");
} else {
setStyle("");
}
}
});

最新更新