首页 > 解决方案 > JavaFX TableView - 更新列表并刷新表后不更新

问题描述

我有这个界面:

//global var
static List<Foo> list = new ArrayList<>();

@Override
public void start(Stage primaryStage){

    TableView<Foo> tableView = new TableView<>();
    tableView.setPlaceholder(new Label("No data"));

    TableColumn<Foo, Integer> colIndex = new TableColumn<>("index");
    colIndex.setCellValueFactory(new PropertyValueFactory<>("index"));

    tableView.getColumns().add(colIndex);
    tableView.setItems(FXCollections.observableArrayList(list));

    Button btn = new Button("update list");
    btn.setOnMouseClicked(e -> {

        Random r = new Random();

        List<Foo> newList = new ArrayList<>();
        newList.add(new Foo(r.nextInt()));
        newList.add(new Foo(r.nextInt()));

        list.clear();
        list.addAll(newList);

        list.forEach(e1 -> System.out.println(e1.getIndex()));

        tableView.refresh();

    });

    VBox vbox = new VBox();
    vbox.getChildren().addAll(btn, tableView);

    primaryStage.setScene(new Scene(vbox));
    primaryStage.show();

}

Foo 类

private int index;

public Foo(int index){
    this.index = index;
}

当我按下按钮时,我想用新值刷新表格list

我的问题是表在tableView.refresh().

为什么表不更新以及如何强制它更新?

标签: javajavafx

解决方案


推荐阅读