Changing background color (or just color) of row (javafx)

我们两清 提交于 2019-12-25 13:14:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!