以下是我写的代码,用来改变皮革表< 200处的行颜色,但我在if条件下面临null指针异常。首先,我从数据库中获取所有数据,并将它们全部添加到表视图中,所以我不希望出现空指针异常。问题出在哪里?
@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("");
}
}
});