简单地说,我有一个带有单列的tableview,我希望对它进行排序,并在每次向可观察列表添加新项时保持排序。我在网上看了几个例子和类似的问题,但没有什么对我有用。如果我尝试从列表的更改侦听器调用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);
}
}
我相信我现在明白了这个问题。当我将一个项目添加到列表时,它调用onChanged()。当我对表进行排序时,它也会触发onChanged,从而创建一个无限循环。我没有意识到该表通过实际更改列表本身来对数据进行排序。