Java Tutorial/Swing/JList — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 15:34, 31 мая 2010

A container for pseud code

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class JListBackground extends JPanel {
  private static final Color lightBlue = new Color(153, 204, 255);
  public JListBackground() {
    super();
    setBackground(lightBlue);
  }
  public static void addComponentsToPane(Container pane) {
    String[] bruteForceCode = { "int count = 0", 
        "int m = mPattern.length();", 
        "int n = mSource .length();", 
        "outer:", 
        " ++count;", 
        " }", 
        " return count;", 
        "}" 
    };
    JList list = new JList(bruteForceCode);
    Border etch = BorderFactory.createEtchedBorder();
    list.setBorder(BorderFactory.createTitledBorder(etch, "Brute Force Code"));
    JPanel listPanel = new JPanel();
    listPanel.add(list);
    listPanel.setBackground(lightBlue);
    list.setBackground(lightBlue);
    pane.add(listPanel, BorderLayout.CENTER);
    pane.setBackground(lightBlue);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Brute Force Algorithm");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addComponentsToPane(frame.getContentPane());
    frame.pack();
    frame.setSize(800, 600);
    frame.setVisible(true);
  }
}





Adding Element-Level Tooltips to List Items

import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ToolTipManager;
public class PropertiesList extends JList {
  public PropertiesList() {
    super(new String[]{ "A", "B", "C", "D", "E", "F", "G", "H" });
    ToolTipManager.sharedInstance().registerComponent(this);
  }
  public String getToolTipText(MouseEvent event) {
    Point p = event.getPoint();
    int location = locationToIndex(p);
    String tip = (String) getModel().getElementAt(location);
    return tip;
  }
  public static void main(String args[]) {
    JFrame frame = new JFrame("Custom Tip Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    PropertiesList list = new PropertiesList();
    
    JScrollPane scrollPane = new JScrollPane(list);
    frame.add(scrollPane);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}





Arranging Items in a JList Component

import javax.swing.JList;
import javax.swing.JScrollPane;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    JScrollPane scrollingList = new JScrollPane(list);
    // The default layout orientation is JList.VERTICAL
    int orient = list.getLayoutOrientation();
    // Change the layout orientation to left-to-right, top-to-bottom
    list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
  }
}





Bench mark for JList

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class JBenchFrame extends JFrame {
  BorderLayout borderLayout1 = new BorderLayout();
  JList list1 = new JList();
  JButton fillButton = new JButton();
  public static void main(String[] args) {
    JBenchFrame bm = new JBenchFrame();
  }
  public JBenchFrame() {
    this.getContentPane().setLayout(borderLayout1);
    this.setSize(new Dimension(400, 300));
    fillButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        ListData ld = new ListData();
        long tmStart = System.currentTimeMillis();
        list1.setModel(ld);
        list1.repaint();
        long tmEnd = System.currentTimeMillis();
        System.out.println(tmEnd - tmStart);
      }
    });
    fillButton.setText("Fill");
    this.getContentPane().add(new JScrollPane(list1), BorderLayout.CENTER);
    this.getContentPane().add(fillButton, BorderLayout.SOUTH);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
  }
}
class ListData extends AbstractListModel {
  String[] strings = new String[10000];
  public ListData() {
    for (int i = 0; i < 10000; i++) {
      strings[i] = "bob" + i;
    }
  }
  public int getSize() {
    return strings.length;
  }
  public Object getElementAt(int index) {
    return strings[index];
  }
}





Creating JList Components

public JList()
JList jlist = new JList();
public JList(Object listData[])
String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H"};
JList jlist = new JList(labels);
public JList(Vector listData)
Vector vector = aBufferedImage.getSources();
JList jlist = new JList(vector);
public JList(ListModel model)
ResultSet results = aJDBCStatement.executeQuery("SELECT colName FROM tableName");
DefaultListModel model = new DefaultListModel();
while (result.next()){
  model.addElement(result.getString(1));
}  
JList jlist = new JList(model);



  1. To improve performance, you can set the fixedCellHeight and fixedCellWidth properties.
  2. Setting these properties is one way to avoid having the JList ask each cell for its rendered size.


Customizing a JList Look and Feel

Property StringObject TypeList.actionMapActionMapList.backgroundColorList.borderBorderList.cellHeightIntegerList.cellRendererListCellRendererList.focusCellHighlightBorderBorderList.focusInputMapInputMapList.focusInputMap.RightToLeftInputMapList.fontFontList.foregroundColorList.lockToPositionOnScrollBooleanList.rendererUseListColors BooleanList.rendererUseUIBorder BooleanList.selectionBackgroundColorList.selectionForegroundColorList.timeFactorLongListUIString


Detecting Double and Triple Clicks on an Item in a JList Component

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    list.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent evt) {
        JList list = (JList) evt.getSource();
        if (evt.getClickCount() == 2) { // Double-click
          int index = list.locationToIndex(evt.getPoint());
        } else if (evt.getClickCount() == 3) { // Triple-click
          int index = list.locationToIndex(evt.getPoint());
        }
      }
    });
  }
}





Get index of first visible item

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    int itemIx = list.getFirstVisibleIndex();
    if (itemIx < 0) {
      // List is either not visible or there are no items
    }
  }
}





Get index of last visible item

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    int itemIx = list.getLastVisibleIndex();
  }
}





JList

The JList component is the basic Swing component for selecting one or more items from a set of choices. Three key elements and their implementations define the JList structure:

  1. A data model for holding the JList data, as defined by the ListModel interface
  2. A cell renderer for drawing the elements of the JList, as described by the ListCellRenderer interface
  3. A selection model for selecting elements of the JList, as described by the ListSelectionModel interface


Listening to JList Events with a ListSelectionListener

If you want to know when elements of a JList have been selected, you need to attach a ListSelectionListener to the JList or the ListSelectionModel.



public interface ListSelectionListener extends EventListener {
  public void valueChanged(ListSelectionEvent e);
}





ListSelectionModel Modes

By default, every JList component is in multiple-selection mode.

ModeDescriptionListSelectionModel.SINGLE_SELECTIONOne item at a time can be selected.ListSelectionModel.SINGLE_INTERVAL_SELECTIONOne contiguous range of items can be selected.ListSelectionModel.MULTIPLE_INTERVAL_SELECTIONAny set of ranges can be selected.



import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class SelectionModeDemo {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Sizing Samples");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DefaultListModel model = new DefaultListModel();
    model.ensureCapacity(100);
    for (int i = 0; i < 100; i++) {
      model.addElement(Integer.toString(i));
    }
    JList jlist2 = new JList(model);
    jlist2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
    
    JScrollPane scrollPane2 = new JScrollPane(jlist2);
    frame.add(scrollPane2, BorderLayout.CENTER);
    frame.setSize(300, 350);
    frame.setVisible(true);
  }
}





Methods are used to find an item

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    String prefix = "b";
    int start = 0;
    
    int itemIx = list.getNextMatch(prefix, start, javax.swing.text.Position.Bias.Forward);
  }
}





Modifying the Data Model

import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class ModifyModelSample {
  static String labels[] = { "A", "B", "C", "D", "E", "F", "G" };
  public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
      model.addElement(labels[i]);
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);
    frame.setSize(640, 300);
    frame.setVisible(true);
  }
}





public Point indexToLocation(int index): returning a Point as the origin of the provided index

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class JListLocationToIndexSample {
  public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H" };
    JFrame frame = new JFrame("Selecting JList");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JList jlist = new JList(labels);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);
    System.out.println(jlist.indexToLocation(5));
    frame.setSize(350, 200);
    frame.setVisible(true);
  }
}





Selection event for double-clicking an item in the list

public int locationToIndex(Point location) in JList: map screen coordinates to list elements



import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class JListLocationToIndexSample {
  public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H" };
    JFrame frame = new JFrame("Selecting JList");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JList jlist = new JList(labels);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);
    MouseListener mouseListener = new MouseAdapter() {
      public void mouseClicked(MouseEvent mouseEvent) {
        JList theList = (JList) mouseEvent.getSource();
        if (mouseEvent.getClickCount() == 2) {
          int index = theList.locationToIndex(mouseEvent.getPoint());
          if (index >= 0) {
            Object o = theList.getModel().getElementAt(index);
            System.out.println("Double-clicked on: " + o.toString());
          }
        }
      }
    };
    jlist.addMouseListener(mouseListener);
    frame.setSize(350, 200);
    frame.setVisible(true);
  }
}





Selection Methods

The class JList supports a list of set and get methods to deal with various selection attributes:



void setSelectedIndex(int index)   
  void setSelectedIndices(int[] indices)   
  void setSelectedValue(Object object, boolean shouldScroll)





Set selected index

You can set an initial selection (s) by using the setSelectedIndex and setSelectedIndices methods (the indexing is zero-based, so index 0 refers to the first option in the JList).



public void setSelectedIndex (int index)
public void setSelectedIndices (int[] indices)





Setting a Tool Tip for an Item in a JList Component

import java.awt.event.MouseEvent;
import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items) {
      // This method is called as the cursor moves within the list.
      public String getToolTipText(MouseEvent evt) {
        // Get item index
        int index = locationToIndex(evt.getPoint());
        // Get item
        Object item = getModel().getElementAt(index);
        // Return the tool tip text
        return "tool tip for " + item;
      }
    };
  }
}





Setting the number of visible rows with setVisibleRowCount()

import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class SizingSamples {
  public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D", "E", "F" ,"G","H","I","J"};
    JFrame frame = new JFrame("Sizing Samples");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JList jlist1 = new JList(labels);
    jlist1.setVisibleRowCount(4);
    DefaultListModel model = new DefaultListModel();
    model.ensureCapacity(100);
    for (int i = 0; i < 100; i++) {
        model.addElement(Integer.toString(i));
    }
    JScrollPane scrollPane1 = new JScrollPane(jlist1);
    frame.add(scrollPane1, BorderLayout.NORTH);
    JList jlist2 = new JList(model);
    jlist2.setVisibleRowCount(4);
    jlist2.setFixedCellHeight(12);
    jlist2.setFixedCellWidth(200);
    JScrollPane scrollPane2 = new JScrollPane(jlist2);
    frame.add(scrollPane2, BorderLayout.CENTER);
    JList jlist3 = new JList(labels);
    jlist3.setVisibleRowCount(4);
    frame.add(jlist3, BorderLayout.SOUTH);
    frame.setSize(300, 350);
    frame.setVisible(true);
  }
}





Sharing the Data Model for a JComboBox and JList

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class SharedDataBetweenComboBoxAndListSample {
  public static void main(String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E", "F", "G" };
    final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);
    JFrame frame = new JFrame("Shared Data");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    JComboBox comboBox1 = new JComboBox(model);
    comboBox1.setEditable(true);
    panel.add(comboBox1);
    frame.add(panel, BorderLayout.NORTH);
    JList jlist = new JList(model);
    JScrollPane scrollPane = new JScrollPane(jlist);
    frame.add(scrollPane, BorderLayout.CENTER);

    JButton button = new JButton("Add");
    frame.add(button, BorderLayout.SOUTH);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        model.addElement("New Added");
      }
    };
    button.addActionListener(actionListener);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Storing value in Vector and adding them into JList

import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class StoringvalueinVectorandaddingthemintoJList {
  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Vector months = new Vector();
    JList list = new JList(months);
    months.addElement("January");
    months.addElement("December");
    frame.add(new JScrollPane(list));
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





These methods can be used to find the range of visible items

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    // Get number of visible items
    int visibleSize = list.getVisibleRowCount();
  }
}





To make multiple list selections, you can use the anchor and lead indices of the selection items.

void setAnchorSelectionIndex(int index)   
  void setLeadSelectionIndex(int index)





To programmatically move the list to the top

The firstVisibleIndex and lastVisibleIndex properties allow you to find out which choices are currently visible. To request that a specific element be made visible, use the public void ensureIndexIsVisible(int index) method.



import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class SizingSamples {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Sizing Samples");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DefaultListModel model = new DefaultListModel();
    model.ensureCapacity(100);
    for (int i = 0; i < 100; i++) {
        model.addElement(Integer.toString(i));
    }
    JList jlist2 = new JList(model);
    
    
    JScrollPane scrollPane2 = new JScrollPane(jlist2);
    frame.add(scrollPane2, BorderLayout.CENTER);
    frame.setSize(300, 350);
    frame.setVisible(true);
    
    jlist2.ensureIndexIsVisible(50);
  }
}





Use drag and drop to reorder a list

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragGestureRecognizer;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import javax.swing.DefaultListModel;
import javax.swing.DropMode;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;
public class DragDropList extends JList {
  DefaultListModel model;
  public DragDropList() {
    super(new DefaultListModel());
    model = (DefaultListModel) getModel();
    setDragEnabled(true);
    setDropMode(DropMode.INSERT);
    setTransferHandler(new MyListDropHandler(this));
    new MyDragListener(this);
    
    model.addElement("a");
    model.addElement("b");
    model.addElement("c");
  }
  public static void main(String[] a){
    JFrame f = new JFrame();
    f.add(new JScrollPane(new DragDropList()));
    f.setSize(300,300);
    f.setVisible(true);
  }
}
class MyDragListener implements DragSourceListener, DragGestureListener {
  DragDropList list;
  DragSource ds = new DragSource();
  public MyDragListener(DragDropList list) {
    this.list = list;
    DragGestureRecognizer dgr = ds.createDefaultDragGestureRecognizer(list,
        DnDConstants.ACTION_MOVE, this);
  }
  public void dragGestureRecognized(DragGestureEvent dge) {
    StringSelection transferable = new StringSelection(Integer.toString(list.getSelectedIndex()));
    ds.startDrag(dge, DragSource.DefaultCopyDrop, transferable, this);
  }
  public void dragEnter(DragSourceDragEvent dsde) {
  }
  public void dragExit(DragSourceEvent dse) {
  }
  public void dragOver(DragSourceDragEvent dsde) {
  }
  public void dragDropEnd(DragSourceDropEvent dsde) {
    if (dsde.getDropSuccess()) {
      System.out.println("Succeeded");
    } else {
      System.out.println("Failed");
    }
  }
  public void dropActionChanged(DragSourceDragEvent dsde) {
  }
}
class MyListDropHandler extends TransferHandler {
  DragDropList list;
  public MyListDropHandler(DragDropList list) {
    this.list = list;
  }
  public boolean canImport(TransferHandler.TransferSupport support) {
    if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
      return false;
    }
    JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
    if (dl.getIndex() == -1) {
      return false;
    } else {
      return true;
    }
  }
  public boolean importData(TransferHandler.TransferSupport support) {
    if (!canImport(support)) {
      return false;
    }
    Transferable transferable = support.getTransferable();
    String indexString;
    try {
      indexString = (String) transferable.getTransferData(DataFlavor.stringFlavor);
    } catch (Exception e) {
      return false;
    }
    int index = Integer.parseInt(indexString);
    JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
    int dropTargetIndex = dl.getIndex();
    System.out.println(dropTargetIndex + " : ");
    System.out.println("inserted");
    return true;
  }
}





Using a Custom Data Model

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.AbstractListModel;
import javax.swing.ruboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
class ArrayListComboBoxModel extends AbstractListModel implements ComboBoxModel {
  private Object selectedItem;
  private ArrayList anArrayList;
  public ArrayListComboBoxModel(ArrayList arrayList) {
    anArrayList = arrayList;
  }
  public Object getSelectedItem() {
    return selectedItem;
  }
  public void setSelectedItem(Object newValue) {
    selectedItem = newValue;
  }
  public int getSize() {
    return anArrayList.size();
  }
  public Object getElementAt(int i) {
    return anArrayList.get(i);
  }
}
public class ArrayListComboBoxModelDemo {
  public static void main(String args[]) {
    JFrame frame = new JFrame("ArrayListComboBoxModel");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ArrayList<Object> arrayList = new ArrayList<Object>();
    arrayList.add("A");
    arrayList.add("B");
    arrayList.add("C");
    ArrayListComboBoxModel model = new ArrayListComboBoxModel(arrayList);
    JComboBox comboBox = new JComboBox(model);
    frame.add(comboBox, BorderLayout.NORTH);
    frame.setSize(300, 225);
    frame.setVisible(true);
  }
}





Using DefaultListModel to control the Data in a JList

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class ModifyModelSampleModelAction {
  static String labels[] = { "A", "B", "C", "D", "E", "F", "G" };
  public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
      model.addElement(labels[i]);
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);
    JButton jb = new JButton("add F");
    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        model.add(0, "First");
        model.clear();
        model.addElement("Last");
        model.addElement("Last");
        model.addElement("Last");
        model.addElement("Last");
        
        int size = model.getSize();
        model.insertElementAt("Middle", size / 2);
        model.set(0, "New First");
        model.setElementAt("New Last", size - 1);
        model.remove(0);
        // model.removeAllElements();
    //    model.removeElement("Last");
  //      model.removeElementAt(size / 2);
//        model.removeRange(0, size / 2);
      }
    });
    frame.add(jb, BorderLayout.SOUTH);
    frame.setSize(640, 300);
    frame.setVisible(true);
  }
}





Using JList

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class JListTest {
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JList Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    String[] selections = { "green", "red", "orange", "dark blue" };
    JList list = new JList(selections);
    list.setSelectedIndex(1);
    System.out.println(list.getSelectedValue());
    frame.add(new JScrollPane(list));
    frame.pack();
    frame.setVisible(true);
  }
}





Using ListDataListener to listen to ListModel Events

To find out when the contents of the list model change, you can register a ListDataListener with the model.

ListDataEvent Type Constants

Type ConstantMethodCONTENTS_CHANGEDcontentsChanged()INTERVAL_ADDEDintervalAdded()INTERVAL_REMOVEDintervalRemoved()



import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
public class ModifyModelSampleListDataListener {
  static String labels[] = { "A", "B", "C", "D", "E", "F", "G" };
  public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
      model.addElement(labels[i]);
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);
    
    ListDataListener listDataListener = new ListDataListener() {
      public void contentsChanged(ListDataEvent listDataEvent) {
        appendEvent(listDataEvent);
      }
      public void intervalAdded(ListDataEvent listDataEvent) {
        appendEvent(listDataEvent);
      }
      public void intervalRemoved(ListDataEvent listDataEvent) {
        appendEvent(listDataEvent);
      }
      private void appendEvent(ListDataEvent listDataEvent) {
        switch (listDataEvent.getType()) {
        case ListDataEvent.CONTENTS_CHANGED:
          System.out.println("Type: Contents Changed");
          break;
        case ListDataEvent.INTERVAL_ADDED:
          System.out.println("Type: Interval Added");
          break;
        case ListDataEvent.INTERVAL_REMOVED:
          System.out.println("Type: Interval Removed");
          break;
        }
        System.out.println(", Index0: " + listDataEvent.getIndex0());
        System.out.println(", Index1: " + listDataEvent.getIndex1());
        DefaultListModel theModel = (DefaultListModel) listDataEvent.getSource();
        System.out.println(theModel);
      }
    };
    model.addListDataListener(listDataListener);
    
    JButton jb = new JButton("add F");
    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        model.add(0, "First");
      }
    });
    
    frame.add(jb,BorderLayout.SOUTH);    
    
    frame.setSize(640, 300);
    frame.setVisible(true);
  }
}