改变行的背景颜色(或只是颜色)(javafx) [英] Changing background color (or just color) of row (javafx)

查看:1322
本文介绍了改变行的背景颜色(或只是颜色)(javafx)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 TableView 。我想根据某些条件更改行的背景颜色。例如,如果balance( getBalance())小于零 - 将该行的背景颜色设置为红色。这是我的 setCellValueFactory

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


推荐答案

使用 TableColumn#setCellFactory 方法。

请尝试以下代码(未经测试):

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

这篇关于改变行的背景颜色(或只是颜色)(javafx)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆