JavaFX sort ListView

Franz Deschler picture Franz Deschler · Dec 30, 2014 · Viewed 13.7k times · Source

I have a ListView in my application and I want to sort the entries. I also want the list to automatically sort if a new entry is added.

For this, I use a SortedList. The Java API says "All changes in the ObservableList are propagated immediately to the SortedList.".

When I run my code below, the output of the command line is exactly what I expect. But the ListView is not sorted.

How can I do this? Thanks!

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();
    }
}

Command line output:

Adam
Brenda
Connie
Derek
Donny
Lynne
Rose
Tony
Williams
Zach

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

Answer

James_D picture James_D · Dec 30, 2014

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);