1

I got a very strange bug in a JavafX application. A cell should be conditionally formatted due to a boolean. If you scroll up and down the ListView, however, the various entries are highlighted in color. However, there is only one entry in the entire list that should be marked.

serialNumberList.setCellFactory(lv -> new ListCell<ListData>() {
    @Override
    protected void updateItem(ListData c, boolean empty) {
        super.updateItem(c, empty);

        if (empty) {
            setText(null);
        } else {
            setText(c.name);
        }

        System.out.println(c);
        if (c != null && c.colored) {
            setStyle("-fx-background-color: #33CEFF");
        }
    }
});

The ListData Class:

String name;
boolean colored = false;
int id;

public ListData(String name, boolean colored, int id) {
    this.name = name;
    this.colored = colored;
    this.id= id;
}

The result before scrolling:

enter image description here

The result after scrolling a few times:

enter image description here

0009laH
  • 1,960
  • 13
  • 27

2 Answers2

2

Thanks to @scary-wombat and to @kleopatra

    serialNumberList.setCellFactory(lv -> new ListCell<ListData>() {
        @Override
        protected void updateItem(ListData c, boolean empty) {
            super.updateItem(c, empty);

            if (empty) {
                setText(null);
            } else {
                setText(c.name);
            }
            System.out.println(c);
            if (c != null && c.colored) {
                setStyle("-fx-background-color: #33CEFF");
            }
            else {
                setStyle(null);
            }
        }
    });

The only thing to do was to set "unstyled"

Thanks!

1

In your cell factory, you have defined a condition where you can paint your cell in blue, but you haven't done the opposite action. In addition, you must insert a condition for empty cells.

You have to modify the end of your updateItem method:

if (c != null && !empty && c.colored)
    setStyle("-fx-background-color: #33CEFF");
else
    setStyle(null);
0009laH
  • 1,960
  • 13
  • 27