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

问题描述 投票:0回答:1

我有一个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()));
javafx tableview javafx-8
1个回答
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("");
            }
        }
    };
});
© www.soinside.com 2019 - 2024. All rights reserved.