Extend AbstractListModel to create custom list model for JList in Java

Description

The following code shows how to extend AbstractListModel to create custom list model for JList.

Example


//from  w w  w  . j a v a  2s .  co m
 
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

public class Main extends JFrame {
  JLabel label = new JLabel();

  public Main() {
    setSize(400, 300);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    JList wordList = new JList(new WordListModel(300000));
    wordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    JScrollPane scrollPane = new JScrollPane(wordList);

    JPanel p = new JPanel();
    p.add(scrollPane);

    getContentPane().add(p, "Center");

    getContentPane().add(label, "North");
  }

  public static void main(String[] args) {
    JFrame frame = new Main();
    frame.setVisible(true);
  }
}

class WordListModel extends AbstractListModel {
  private int length;

  public WordListModel(int n) {
    length = n;
  }

  public int getSize() {
    return length;
  }

  public Object getElementAt(int n) {
    return Integer.toString(n);
  }
}

The code above generates the following result.

Extend AbstractListModel to create custom list model for JList in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer