Change row color in TableView JavaFX according to its value

1

Good morning!

To the point I have an interface where I show a table with two columns, the first one is Placa and the other is Mileage. What I want to do is to get that according to the value that the Mileage column has in its cell its Background color change Example: Plate: 0001 Mileage: 5000 If Mileage is greater than or equal to 5000 , paint Red. Here I show my table: Here is the code that shows the table:

 @Override
public void initialize(URL url, ResourceBundle rb) {
    conexion = new Conexion();
    conexion.establecerConexion();

    informacionAlertas = FXCollections.observableArrayList();
    Menu.mostrarTablaAlertasMenu(conexion.getConnection(), informacionAlertas);
    tblInformacion.setItems(informacionAlertas);

    clmnAlertaPlaca.setCellValueFactory(new PropertyValueFactory<>("AlertaPlaca"));
    clmnAlertaKmRest.setCellValueFactory(new PropertyValueFactory<>("AlertaKmRest"));






}
    
asked by Riddick 06.10.2017 в 18:25
source

1 answer

1

I pass an example code that you should adapt to your problem but that I think will be a guide to solve your problem:

TableColumn<Object, Integer> columna = new TableColumn<>();
columna.setCellFactory(new Callback<TableColumn<Object,Integer>, TableCell<Object,Integer>>(){
        @Override
        public TableCell<Object, Integer> call(TableColumn<Object, Integer> tablecolumn) {
            return new TableCell<Object,Integer>(){
                @Override
                protected void updateItem(Integer item, boolean empty) {
                    super.updateItem(item, empty);

                    if (item != null){
                        if (item.intValue() > 5000){
                            setStyle("-fx-background-color: red;");
                        }
                        else if (item.intValue() == 200){
                            setStyle("-fx-background-color: green;");
                        }
                    }

                }
            };
        }
    });

The really important thing is to assign a CellFactory to your column, and when returning the TableCell to render, overwrite the updateItem and do your logic there to customize the cell.

    
answered by 06.10.2017 в 22:11