How to conditionally format JavaFX ComboBoxTableCell label

Viewed 151

I assume it is possible to conditionally format JavaFX ComboBoxTableCell label according to following JavaFX 11 documentation items:

By default, the ComboBoxTableCell is rendered as a Label when not being edited [...].

  • Labeled class setTextFill method description:

Sets the value of the property textFill.

If my assumption is correct, I would like to know how to modify following SSCCE so that any ComboBoxTableCell label textFill property is set to following Paint values. Thank you!

  1. Color.Red if its value is not valid

enter image description here

  1. Color.Blue if its value is set for different rows.

enter image description here

public class PersonInRoom extends Application
{
    private final ObservableList<Person> data = FXCollections.observableArrayList(
        new Person("Jacob"   , "Kitchen"),
        new Person("Isabella", "Bedroom"),
        new Person("Ethan"   , "Attic"));

    TableView<Person> table ;

    public static void main(String[] args) {launch(args);}

    @Override
    public void start(Stage stage)
    {
        TableColumn nameCol = new TableColumn("Name");
        nameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("name"));

        TableColumn roomCol = new TableColumn("Room");
        roomCol.setCellValueFactory(new PropertyValueFactory<Person, String>("room"));
        roomCol.setCellFactory(ComboBoxTableCell.forTableColumn("Bathroom", "Bedroom", "Kitchen"));
        roomCol.setOnEditCommit((EventHandler<CellEditEvent<Person, String>>) t -> t.getTableView().getItems().get(t.getTablePosition().getRow()).setRoom(t.getNewValue()));

        table = new TableView<>();
        table.setEditable(true);
        table.setItems(data);
        table.getColumns().addAll(nameCol, roomCol);

        VBox vbox = new VBox();
        vbox.getChildren().addAll(table);

        Scene scene = new Scene(vbox);
        stage.setScene(scene);
        stage.show();
    }

    public static class Person
    {
        private final SimpleStringProperty name;
        private final SimpleStringProperty room;
        private Person(String name, String room)
        {
            this.name = new SimpleStringProperty(name);
            this.room = new SimpleStringProperty(room);
        }
        public String getName()         {return name.get();}
        public String getRoom()         {return room.get();}
        public void   setRoom(String r) {room.set(r);}
    }
}
1 Answers

As suggested by kleopatra in 2020-09-28 03:30:59Z comment to the question asked at the top of this page:

You need a custom cell and override updateItem to set the color depending on context.

... I created a custom cell (a ComboBoxTableCell to be accurate) and overrode its updateItem method.

Feel free to re-use it (see source code below) but please pay attention to kleopatra's comment posted for this answer on 2020-09-28 03:30:59Z:

You are probably aware that the logic itself doesn't belong into the view (aka: cell) - it should be handled "near" the model, including a notification path (vs. hacking around by calling refresh).

public class PersonInRoom extends Application
{
    private final ObservableList<Person> data = FXCollections.observableArrayList(
        new Person("Jacob", "Kitchen"),
        new Person("Isabella", "Bedroom"),
        new Person("Ethan", "Attic"));
    TableView<Person> table;

    public static void main(String[] args) {launch(args);}

    @Override
    public void start(Stage stage)
    {
        TableColumn nameCol = new TableColumn("Name");
        nameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("name"));

        TableColumn roomCol = new TableColumn("Room");
        roomCol.setCellValueFactory(new PropertyValueFactory<Person, String>("room"));

        roomCol.setCellFactory(new Callback<TableColumn<Person, String>, ComboBoxTableCell<Person, String>>()
        {
            @Override
            public ComboBoxTableCell<Person, String> call(TableColumn<Person, String> personStringTableColumn)
            {
                String rooms[] = {"Bathroom", "Bedroom", "Kitchen"};
                return new ComboBoxTableCell<>(rooms)
                {
                    @Override
                    public void updateItem(String item, boolean empty)
                    {
                        super.updateItem(item, empty);
                        if (!empty) {
                            setText(item);
                            boolean found = false;
                            for (int i = 0; i < rooms.length; i++) {
                                if (rooms[i].equals(item)) {
                                    found = true;
                                    break;
                                }
                            }
                            if (!found) {
                                setTextFill(Color.RED);
                                return;
                            }
                            int count = 0;
                            for (int i = 0; i < data.size(); i++) {
                                if (data.get(i).getRoom().equals(item)) {
                                    if (++count > 1) {
                                        setTextFill(Color.BLUE);
                                        return;
                                    }
                                }
                            }
                            setTextFill(Color.BLACK);
                        }
                    }

                };
            }
        });

        roomCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>()
        {
            @Override
            public void handle(CellEditEvent<Person, String> cellEditEvent)
            {
                cellEditEvent.getTableView().getItems().get(cellEditEvent.getTablePosition().getRow()).setRoom(cellEditEvent.getNewValue());
                table.refresh();
            }
        });


        table = new TableView<>();
        table.setEditable(true);
        table.setItems(data);
        table.getColumns().addAll(nameCol, roomCol);

        VBox vbox = new VBox();
        vbox.getChildren().addAll(table);

        Scene scene = new Scene(vbox);
        stage.setScene(scene);
        stage.show();
    }


    public static class Person
    {
        private final SimpleStringProperty name;
        private final SimpleStringProperty room;

        private Person(String name, String room)
        {
            this.name = new SimpleStringProperty(name);
            this.room = new SimpleStringProperty(room);
        }

        public String getName()       {return name.get();}
        public String getRoom()       {return room.get();}
        public void setRoom(String r) {room.set(r);}
    }
}
Related