Extend DefaultListModel to create an array based model for JList in Java

Description

The following code shows how to extend DefaultListModel to create an array based model for JList.

Example


  /*w  ww  . j a  v  a2s .c o m*/

import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

class MyListModel extends DefaultListModel {
  protected int[] count = new int[100];

  public Object getElementAt(int index) {
    if (index < 100) {
      count[index]++;
    }
    return super.elementAt(index);
  }

}
public class Main extends JFrame {
  MyListModel model = new MyListModel();

  public Main() {
    for (int i = 0; i < 25; i++) {
      model.addElement("A" + i);
    }
    JList list = new JList(model);
    getContentPane().add(new JScrollPane(list), BorderLayout.CENTER);

    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    pack();
    setVisible(true);
  }

  public static void main(String arg[]) {
    new Main();
  }
}

The code above generates the following result.

Extend DefaultListModel to create an array based 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