Jlist alphabetical ordering

I have the following demo application that displays a list of values, but I need to be able to control the ordering of the items in the list. 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(); } } 
+4
source share
5 answers

The easiest way is to use SwingX, which supports JXList sorting / filtering in the same way as sorting / filtering the main table:

 JXList list = new JXList(model); list.setAutoCreateRowSorter(true); list.toggleSortOrder(); 
+7
source

If you mean, you need to control the order of its elements at runtime while its elements are changing, then you probably need to implement your own SortedListModel for your JList. A good oracle article can be found here .

+3
source

If you do not need the problem of sorting objects before adding them to the JList, you can write / use a ListModel implementation that will sort them for you already. See this implementation .

As I have said in almost all issues related to JLists / JTables, please see GlazedLists . It does almost everything you can imagine regarding sorting and filtering.

+2
source

DefaultListModel displays elements in the order in which they are added. You can simply add items to the order and that they will be displayed.

0
source

You can use the Sorted combo box model . I know this is a "combo box", but it also implements the List interface.

0
source

Source: https://habr.com/ru/post/1346747/


All Articles