JavaFX sort ListView

14,782

Solution 1

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

Solution 2

For Java 8:

listView.setItems(names.sorted());
Share:
14,782
Franz Deschler
Author by

Franz Deschler

Updated on June 27, 2022

Comments

  • Franz Deschler
    Franz Deschler almost 2 years

    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