Autoupdating rows in TableView from model
Asked Answered
S

2

6

I've been looking information about refreshing data into a tableview. I was trying modifying directly the model, but I get a bug. I modify the model, but the table doesn't refreshed, only when I move a column, the table shows the modified values.

To show you an example (13-6) I take the tutorial:

http://docs.oracle.com/javafx/2/ui_controls/table-view.htm#CJABIEED

And I modify it including a button and in its action:

Button button = new Button("Modify");
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
    String name = table.getItems().get(0).getFirstName();
    name = name + "aaaa";
    table.getItems().get(0).setFirstName(name);
    }
});

final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.getChildren().addAll(label, table, button);
vbox.setPadding(new Insets(10, 0, 0, 10));

I guess that it's a bug in the tableview, but is there any chance to fix this?

Thank you!

Subsequent answered 6/6, 2012 at 10:47 Comment(0)
H
22

to make TableView able to track data changes you need to expose relevant fields as JavaFX properties. Add next methods to Person class from tutorial:

    public SimpleStringProperty firstNameProperty() {
        return firstName;
    }

    public SimpleStringProperty lastNameProperty() {
        return lastName;
    }

    public SimpleStringProperty emailProperty() {
        return email;
    }
Herbie answered 6/6, 2012 at 12:37 Comment(2)
It simply works. It's just what I was looking for. Thank you!Subsequent
Great! I guess it works with reflection, so it's important the property getters have the right name [attribute]Property(). In my case I had get[attribute]Property() so it wasn't updating. Thanks!Hanny
C
3

There is a bug in TableView update (https://javafx-jira.kenai.com/browse/RT-22463). I had similar problem and after some search this is my workaround. I found that if the columns are removed and then re-added the table is updated.

public static <T,U> void refreshTableView(TableView<T> tableView, List<TableColumn<T,U>> columns, List<T> rows) {        
    tableView.getColumns().clear();
    tableView.getColumns().addAll(columns);

    ObservableList<T> list = FXCollections.observableArrayList(rows);
    tableView.setItems(list);
}


Example of usage:

refreshTableView(myTableView, Arrays.asList(col1, col2, col3), rows);
Claudelle answered 4/9, 2013 at 0:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.