3

我的应用程序中有一个 ListView,我想对条目进行排序。如果添加了新条目,我还希望列表自动排序。

为此,我使用了一个 SortedList。Java API 说“ObservableList 中的所有更改都会立即传播到 SortedList。”。

当我在下面运行我的代码时,命令行的输出正是我所期望的。但是 ListView 没有排序。

我怎样才能做到这一点?谢谢!

public class Test extends Application
{
    public static final ObservableList names = FXCollections.observableArrayList();

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

    @Override
    public void start(Stage primaryStage) {
        final ListView listView = new ListView(names);
        listView.setPrefSize(200, 250);
        listView.setEditable(true);

        names.addAll("Brenda", "Adam", "Williams", "Zach", "Connie", "Donny", "Lynne", "Rose", "Tony", "Derek");

        listView.setItems(names);
        SortedList<String> sortedList = new SortedList(names);
        sortedList.setComparator(new Comparator<String>(){
            @Override
            public int compare(String arg0, String arg1) {
                return arg0.compareToIgnoreCase(arg1);
            }
        });

        for(String s : sortedList)
            System.out.println(s);
        System.out.println();

        names.add("Foo");
        System.out.println("'Foo' added");
        for(String s : sortedList)
            System.out.println(s);

        StackPane root = new StackPane();
        root.getChildren().add(listView);
        primaryStage.setScene(new Scene(root, 200, 250));
        primaryStage.show();
    }
}

命令行输出:

Adam
Brenda
Connie
Derek
Donny
Lynne
Rose
Tony
Williams
Zach

'Foo' added
Adam
Brenda
Connie
Derek
Donny
Foo    <--
Lynne
Rose
Tony
Williams
Zach
4

3 回答 3

9

You need to use the SortedList in the ListView. I.e. do

    final ListView listView = new ListView();
    listView.setPrefSize(200, 250);
    listView.setEditable(true);

    names.addAll("Brenda", "Adam", "Williams", "Zach", "Connie", "Donny", "Lynne", "Rose", "Tony", "Derek");

    SortedList<String> sortedList = new SortedList(names);
    listView.setItems(sortedList);
于 2014-12-30T20:38:40.310 回答
4

对于 Java 8:

listView.setItems(names.sorted());
于 2017-06-30T19:13:35.510 回答
0

在 Java 8 中,您也可以listView.getItems().sort([Some Comparator])这样尝试:

listView.getItems().sort((o1,o2)->{
    if(o1.equals(o2)) return 0;
    if(o1.val > o2.val) 
        return 1; 
    else 
        return 0;
});
于 2019-03-22T16:49:19.110 回答