Search code examples
cssjavafxtableviewcss-specificitytablecolumn

JavaFX Tableview make specific cells colored


TableColumn tc = new TableColumn();

tc.getStyleClass.add(".style in css file")

i set up the tablecolumn with css file. and i want to make each cell has different backgrounds. is there any way to do it?

tableColumn row 1 bakcground color = green, row2 = red, row3 = blue....etc


Solution

  • You have to use setRowFactory for your TableView and change row style. A little example there:

    tableView.setRowFactory(new Callback<TableView<Data_type>, TableRow<Data_type>>(){
                //There can define some colors.
                int color = 0;
                String colors[] = new String[]{"red","blue","green"};
                @Override
                public TableRow<Data_type> call(TableView<Data_type> param) {
                    final TableRow<Data_type> row = new TableRow<Data_type>() {
                        @Override
                        protected void updateItem(Data_type item, boolean empty) {
                            super.updateItem(item, empty);
                            //there write your code to stylize row
                            if(getIndex() > -1){
                                String color = colors[getIndex() % 3];
                                setStyle("-fx-background-color: "+ color + ";");
    
                            }
                        }
                    };
                    return row;
                }
            });
    

    Result:
    enter image description here