0

Why does a

tableColumn.setCellValueFactory(new PropertyValueFactory<Object1, Integer>("Number")); 

method call the getNumber method multiple times when I only add one row to a tableView?

The number field is in object2 that is used in object1. So here Object1 one provides a getNumber method that gets a number stored in an arraylist in object2.

Here is my getNumber method:

public double getNumber() {
    setNumber++;
    return sets.get(setNumber).getNumber();
}

1 Answers1

0

The value is fetched when the TableView shows it. When you modify your value when it is retrieved, you are just doing that and you just count the fetches.

Imagine you have a TableView with 10 visible rows and 20 entries in the list. When you scroll down and up, the value is fetched for the rows which newly appear in the visible area.

If you try this:

public class SO extends Application {
    public static class Item {
        final int v;
        Item(int v) { this.v = v; }
        public int getV() {
            System.out.println(v);
            return v;
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        StackPane pane = new StackPane();
        Scene scene = new Scene(pane, 300, 100);
        primaryStage.setScene(scene);
        ObservableList<Item> list = FXCollections.observableArrayList();
        for (int i=0; i<20; i++) {
            Item item = new Item(i);
            list.add(item);
        }
        TableView<Item> tv = new TableView<>(list);
        TableColumn<Item, String> col = new TableColumn<>("Column");
        col.setCellValueFactory(new PropertyValueFactory<Item,String>("v"));
        tv.getColumns().add(col);
        pane.getChildren().add(tv);
        primaryStage.show();
    }

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

}

When scrolling the TableView to the end, it will print increasing numbers in the console. When scrolling back, it prints decreasing numbers as it displays values from the beginning of the list. Part of the output:

5
6
7
8
9
9
2
2
1
1
0
Rainer Schwarze
  • 4,725
  • 1
  • 27
  • 49