extends DefaultListModel : JList Model « Swing « Java Tutorial






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 void dump() {
    for (int i = 0; i < 100; i++) {
      if (count[i] != 0) {
        System.out.println(i + "\t" + count[i] + "\t\t" + elementAt(i));
      }
    }
  }
}
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) {
        model.dump();
        System.exit(0);
      }
    });

    pack();
    setVisible(true);
  }

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








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