SortedListModel: sortable JList : JList Model « Swing « Java Tutorial

SortedListModel: sortable JList
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);
    fireContentsChanged(this, 0, getSize());

  public void 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();
    JFrame frame = new JFrame("Selecting JList");
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);

    frame.setSize(350, 200);

14.42.JList Model
14.42.1.SortedListModel: sortable JListSortedListModel: sortable JList
14.42.2.extends DefaultListModel
14.42.3.extends AbstractListModelextends AbstractListModel
14.42.4.JList: ListModel and ListSelectionModel. The ListModel handles data. ListSelectionModel works with the GUI.
14.42.5.Create a list that allows adds and removes
14.42.6.Append an item
14.42.7.Insert an item at the beginning
14.42.8.Adding and Removing an Item in a JList Component
14.42.9.Set method replaces an item
14.42.10.Methods are used to remove items
14.42.11.DefaultListModel and JList
14.42.12.Getting the Items in a JList Component