Creating a sorted JList

This example shows you a method sortList that gets the JList data, puts them in an array, sorts them using Arrays.sort and updates the list model:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
 
      final DefaultListModel listModel = new DefaultListModel();   
 
      // populate listmodel
      Random r = new Random();
      for (int i=0; i<50; i++) {
         listModel.addElement("list item # " + (Math.abs(r.nextInt()) % 100));
      }
 
      final JList list = new JList(listModel); 
 
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(list));    
      JButton sortButton = new JButton("Sort");
      sortButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            sortList(list);
         }
      });
      getContentPane().add(BorderLayout.SOUTH, sortButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public void sortList(JList list) {
      ListModel model = list.getModel();
 
      int n = model.getSize();
      String[] data = new String[n]; 
 
      for (int i=0; i<n; i++) { 
         data[i] = (String) model.getElementAt(i); 
      }
 
      Arrays.sort(data); 
 
      list.setListData(data); 
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}