问题
I've a TableView
. I want to change background color of rows according to some condition. For instance, if balance (getBalance()
) is less than zero - set background color of that row to red. Here is my setCellValueFactory
:
tc_proj_number.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getId().toString()));
tc_proj_date.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getValueDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString()));
tc_proj_amount.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getBalance().setScale(2).toPlainString()));
tc_proj_comment.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getComment()));
回答1:
Use TableColumn#setCellFactory method.
Try the following code (not tested):
tc_proj_amount.setCellFactory(column -> {
return new TableCell<Account, String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(item);
// Style row where balance < 0 with a different color.
BigDecimal balance = new BigDecimal(item);
TableRow currentRow = getTableRow();
if (balance.compareTo(BigDecimal.valueOf(0)) < 0) {
currentRow.setStyle("-fx-background-color: red;");
} else currentRow.setStyle("");
}
}
};
});
来源:https://stackoverflow.com/questions/31902910/changing-background-color-or-just-color-of-row-javafx