Skip to main content

Creating Sorted JList Components

Posted by joconner on June 6, 2006 at 9:37 PM PDT

My personal digital assistant (PDA) provides contact information for friends, family, and coworkers. The PDA allows me to find a person's phone number easily by searching on that person's name. The information is sorted according to standard dictionary-sort order for the contact's name. That is, the name Michèle comes before Robert in the list. Without this sort order, I would have difficulty finding names quickly and easily.

Java technology programmers use the javax.swing.JList component to provide list views of similar data, whether it be a phone contact list or a grocery list. Despite the convenience of this user interface (UI) component, a JList doesn't sort its elements. It displays them in the same order provided by its underlying javax.swing.ListModel interface. Neither the ListModel interface nor the javax.swing.DefaultListModel class provides sorted data. Instead, the default model provides its content in the same order as you enter it. If you enter unsorted data -- for example, the letters B, C, and A -- the model provides it to list components without sorting it to either ascending order -- A, B, C -- or to descending order -- C, B, A. Lists are appropriate UI components for many applications, but an unsorted list has limited usefulness.

This article describes how to produce sorted lists and uses a simple application to demonstrate concepts. You can download all the demo source code using the link at the end of this article. Although I developed the demo source as a NetBeans IDE 5.0 project, the demo's ANT script does not require that you use that IDE to compile or execute the application. The demo application uses the decorator design pattern to provide additional functionality to the ListModel object you already use. This allows you to use and benefit from a sorted model after making only minimal changes to your existing application code base. You really can have your list model and sort it too.

Article link: Creating a Sorted JList Component

Related Topics >>