Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JList alphabetical ordering

Tags:

java

swing

I have the following demo app which displays a list of values, but i need to be able to control the ordering of the elements in the list. Whats the easiest way to add this?

package demo;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListModel;

public class JListOrder {

    public JListOrder()
    {
        JFrame frame = new JFrame("JListOrder");

        DefaultListModel model = new DefaultListModel();
        model.addElement("z");
        model.addElement("Z");
        model.addElement("a");
        model.addElement("A");
        model.addElement("C");
        model.addElement("c");
        model.addElement("b");
        model.addElement("B");

        JList list = new JList(model);
        frame.add(list);
        frame.setSize(200,200);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new JListOrder();
    }
}
like image 669
emeraldjava Avatar asked Dec 17 '22 15:12

emeraldjava


1 Answers

The easiest way is to use SwingX which supports sorting/filtering of JXList the same way as core table sorting/filtering:

JXList list = new JXList(model);
list.setAutoCreateRowSorter(true);
list.toggleSortOrder();
like image 129
kleopatra Avatar answered Dec 28 '22 07:12

kleopatra