【问题标题】:Errors when sorting a tableview对表格视图进行排序时出错
【发布时间】:2019-04-19 18:51:17
【问题描述】:

简单地说,我有一个带有单列的表格视图,每当我向可观察列表中添加新项目时,我希望对其进行排序并保持排序。我在网上查看了几个示例和类似的问题,但没有什么对我有用。如果我尝试从列表的更改侦听器中调用 TableView.sort(),似乎什么都没有发生。

当我将列添加到表的排序顺序时,就会出现问题。在此之后尝试对表进行排序会导致应用程序严重崩溃。唯一的错误是“应用程序启动方法中的异常”。然后我将 sort() 调用移至 Platform.runLater() 并防止应用程序崩溃。但随后又出现了一个新问题。调用 sort 时,我会得到一个数组索引越界错误,这似乎是随机发生的,尽管我认为主要是当新项目超出表的视图并需要滚动条时。

在编写本文时,我将排序从更改侦听器中移出,并移到了添加实际数据的任务中。没有更多的错误。所以我想我的新问题是,为什么我在尝试从听众那里做事时会遇到这么多问题?

public class Temp extends Application{


    private ObservableList<String> libraryList = FXCollections.observableArrayList();


    public void start(Stage stage) {

        Label statusLabel = new Label("stuff goes here");

        TableView<String> table = new TableView<String>(libraryList);
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        TableColumn<String, String> col = new TableColumn<String, String>("Stuff");
        col.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue()));
        table.getColumns().add(col);
        table.getSortOrder().add(col);





        libraryList.addListener(new ListChangeListener<String>() {
            public void onChanged(Change change) {


                Platform.runLater(()->{
                    table.sort();
                    statusLabel.setText(libraryList.size()+" entries");
                });

            }

        });





        // dummy stuff
        libraryList.add("foo");
        libraryList.add("bar");



        Button b = new Button("Press Me");
        b.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                FileTask task = new FileTask();
                new Thread(task).start();
            }
        });


        BorderPane mainBody = new BorderPane();

        mainBody.setTop(statusLabel);
        mainBody.setCenter(table);
        mainBody.setBottom(b);
        Scene scene = new Scene(mainBody);
        stage.setScene(scene);
        stage.show();

    }








    class FileTask extends Task<Boolean>{

        public FileTask(){

        }


        protected Boolean call() throws Exception{

            Random rand = new Random();
            for(int i = 0; i < 3; i++) {
                String s = ""+rand.nextInt(Integer.MAX_VALUE);
                libraryList.add(s);
            }

            return true;
        }



    }







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

    }
}

【问题讨论】:

    标签: java sorting javafx tableview


    【解决方案1】:

    我相信我现在明白了这个问题。当我将一个项目添加到列表中时,它会调用 onChanged()。当我对表格进行排序时,它也会触发 onChanged 从而创建一个无限循环。我没有意识到表格是通过实际更改列表本身来对数据进行排序的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多