Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFx Set Tableview Cell Background Color Dynamically

Tags:

java

javafx-2

I want to add color to the color cell of the rows dynamically when ADD button is clicked. I am not able to change the background color of the cell. Please see the image for reference. Am not able to achieve that with the help of code. Thanks for help in advance.

Snippet adding values to table :

     @FXML
     private void addEntity() {

      data.add(new Inventory(codeTemp.getText(), articleNameTemp.getText(), Integer.parseInt(amountTemp.getText()), dcTemp.isSelected() ? true:false, stTemp.isSelected()?true:false, Utilities.toRGBCode(colorTemp.getValue()), informationTemp.getText(), data.size()+1));
      inventoryTable.setItems(data);

     }

enter image description here

like image 340
gursahib.singh.sahni Avatar asked Sep 01 '14 08:09

gursahib.singh.sahni


1 Answers

Did with the help of a callback on the column.

        Callback<TableColumn<Inventory, String>, TableCell<Inventory, String>> cellFactory =
        new Callback<TableColumn<Inventory, String>, TableCell<Inventory, String>>() {
            public TableCell call(TableColumn p) {
                TableCell cell = new TableCell<Person, String>() {
                    @Override
                    public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        setText(empty ? null : getString());
                        setStyle("-fx-background-color:"+getString());
                    }

                    private String getString() {
                        return getItem() == null ? "" : getItem().toString();
                    }
                };


                return cell;
            }
        };

enter image description here

like image 80
gursahib.singh.sahni Avatar answered Nov 10 '22 08:11

gursahib.singh.sahni