JavaFX TableView: format one cell based on the value of another in the row

后端 未结 1 1136
傲寒
傲寒 2020-12-16 07:40

I have a class named TransactionWrapper I\'m using to populate my ObservableList for the TableView in my application. This wrapper has an attribute (enum) indicating whether

相关标签:
1条回答
  • 2020-12-16 08:12

    Figured it out! Thanks for the idea James, but I went a bit of a different way. Here's the code for anyone in the future reading this post:

    amountCol.setCellFactory(new Callback<TableColumn<TransactionWrapper, String>, 
                TableCell<TransactionWrapper, String>>()
                {
                    @Override
                    public TableCell<TransactionWrapper, String> call(
                            TableColumn<TransactionWrapper, String> param)
                    {
                        return new TableCell<TransactionWrapper, String>()
                        {
                            @Override
                            protected void updateItem(String item, boolean empty)
                            {
                                if (!empty)
                                {
                                    int currentIndex = indexProperty()
                                            .getValue() < 0 ? 0
                                            : indexProperty().getValue();
                                    TransactionTypes type = param
                                            .getTableView().getItems()
                                            .get(currentIndex).getTransaction()
                                            .getTransactionType();
                                    if (type.equals(TransactionTypes.DEPOSIT))
                                    {
                                        setTextFill(Color.GREEN);
                                        setText("+ " + item);
                                    } else
                                    {
                                        setTextFill(Color.RED);
                                        setText("- " + item);
                                    }
                                }
                            }
                        };
                    }
                });
    

    The param.getTableView().getItems().get(currentIndex) was key.. had to drill into the parent a bit there, but it got the job done. The biggest challange there was finding the index. Felt a bit silly when I figure out that the indexProperty() function existed.. lol. Didn't think to look at the class level functions that were available. Happy coding!

    0 讨论(0)
提交回复
热议问题