Java tutorial
import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.*; import java.util.*; class SortedListModel extends AbstractListModel { SortedSet<Object> model; public SortedListModel() { model = new TreeSet<Object>(); } public int getSize() { return model.size(); } public Object getElementAt(int index) { return model.toArray()[index]; } public void add(Object element) { if (model.add(element)) { fireContentsChanged(this, 0, getSize()); } } public void addAll(Object elements[]) { Collection<Object> c = Arrays.asList(elements); model.addAll(c); fireContentsChanged(this, 0, getSize()); } public void clear() { model.clear(); fireContentsChanged(this, 0, getSize()); } public boolean contains(Object element) { return model.contains(element); } public Object firstElement() { return model.first(); } public Iterator iterator() { return model.iterator(); } public Object lastElement() { return model.last(); } public boolean removeElement(Object element) { boolean removed = model.remove(element); if (removed) { fireContentsChanged(this, 0, getSize()); } return removed; } } public class JListLocationToIndexSample { public static void main(String args[]) { SortedListModel model = new SortedListModel(); model.add("A"); model.add("C"); model.add("Z"); model.add("B"); JFrame frame = new JFrame("Selecting JList"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JList jlist = new JList(model); JScrollPane scrollPane1 = new JScrollPane(jlist); frame.add(scrollPane1, BorderLayout.CENTER); frame.setSize(350, 200); frame.setVisible(true); } }