改变行的背景颜色(或只是颜色)(javafx)

时间:2015-08-09 09:48:12

标签: javafx tableview javafx-8

我是TableView。我想根据某些条件更改行的背景颜色。例如,如果balance(getBalance())小于零 - 将该行的背景颜色设置为红色。这是我的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 个答案:

答案 0 :(得分:3)

使用TableColumn#setCellFactory方法 请尝试以下代码(未经测试):

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("");
            }
        }
    };
});