更改 javaFX 中的特定行颜色
Change specific row color in javaFX
这是我编写的代码,用于更改皮革表 < 200 处的行颜色,但在 if 条件下我遇到空指针异常。首先,我从数据库中获取所有数据并将它们全部添加到 table 视图中,因此我不希望出现空指针异常。有什么问题?
@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("");
}
}
});
这是我编写的代码,用于更改皮革表 < 200 处的行颜色,但在 if 条件下我遇到空指针异常。首先,我从数据库中获取所有数据并将它们全部添加到 table 视图中,因此我不希望出现空指针异常。有什么问题?
@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("");
}
}
});