Java by API/javax.swing/JList — различия между версиями

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

Версия 17:43, 31 мая 2010

extends JList (custom tooltops)

  
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ToolTipManager;
public class MainClass extends JList {
  SortedListModel model;
  Properties tipProps;
  public MainClass(Properties props) {
    model = new SortedListModel();
    setModel(model);
    ToolTipManager.sharedInstance().registerComponent(this);
    tipProps = props;
    addProperties(props);
  }
  private void addProperties(Properties props) {
    Enumeration names = props.propertyNames();
    while (names.hasMoreElements()) {
      model.add(names.nextElement());
    }
  }
  public String getToolTipText(MouseEvent event) {
    Point p = event.getPoint();
    int location = locationToIndex(p);
    String key = (String) model.getElementAt(location);
    String tip = tipProps.getProperty(key);
    return tip;
  }
  public static void main(String args[]) {
    JFrame frame = new JFrame("Custom Tip Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Properties props = System.getProperties();
    MainClass list = new MainClass(props);
    JScrollPane scrollPane = new JScrollPane(list);
    frame.add(scrollPane);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class SortedListModel extends AbstractListModel {
  SortedSet<Object> model;
  public SortedListModel() {
    model = new TreeSet<Object>();
  }
  public int getSize() {
    return model.size();
  }
  public Object getElementAt(int index) {
    return model.toArray()[index];
  }
  public void add(Object element) {
    if (model.add(element)) {
      fireContentsChanged(this, 0, getSize());
    }
  }
  public void addAll(Object elements[]) {
    Collection<Object> c = Arrays.asList(elements);
    model.addAll(c);
    fireContentsChanged(this, 0, getSize());
  }
  public void clear() {
    model.clear();
    fireContentsChanged(this, 0, getSize());
  }
  public boolean contains(Object element) {
    return model.contains(element);
  }
  public Object firstElement() {
    return model.first();
  }
  public Iterator iterator() {
    return model.iterator();
  }
  public Object lastElement() {
    return model.last();
  }
  public boolean removeElement(Object element) {
    boolean removed = model.remove(element);
    if (removed) {
      fireContentsChanged(this, 0, getSize());
    }
    return removed;
  }
}





JList: addListSelectionListener(ListSelectionListener listener)

  
/*
 java.util.ArrayList: 
 java.util.ArrayList: Collection 
 java.util.ArrayList: int 
 
 */
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class MainClass extends JFrame {
  JList list = null;
  MainClass() {
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    ArrayList data = new ArrayList();
    data.add("Hi");
    data.add("Hello");
    data.add("Goodbye");
     list = new JList(data.toArray());
    list.addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent evt) {
        if (evt.getValueIsAdjusting())
          return;
        System.out.println("Selected from " + evt.getFirstIndex() + " to " + evt.getLastIndex());
      }
    });
    cp.add(new JScrollPane(list), BorderLayout.CENTER);
  }
  public static void main(String[] s) {
    MainClass l = new MainClass();
    l.pack();
    l.setVisible(true);
  }
}





JList: addMouseListener(MouseListener lis)

  
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 MainClass {
  public static void main(final String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E" };
    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);
    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);
  }
}





JList: addSelectionInterval(int anchor, int lead)

  

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 start = 2;
    int end = 2;
    list.addSelectionInterval(start, end); 
  }
}





JList: clearSelection()

  
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.clearSelection();
  }
}





JList: getFirstVisibleIndex()

  

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
    }
  }
}





JList: getLastVisibleIndex()

  
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: getLayoutOrientation()

  

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);
  }
}





JList: getMaxSelectionIndex()

  
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 lastSelIx = list.getMaxSelectionIndex();
  }
}





JList: getNextMatch(String prefix, int startIndex, Bias bias)

  
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);
  }
}





JList: getSelectedIndices()

  
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class MainClass {
  public static void main(final String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E" };
    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);
    ListSelectionListener listSelectionListener = new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent listSelectionEvent) {
        System.out.println("First index: " + listSelectionEvent.getFirstIndex());
        System.out.println(", Last index: " + listSelectionEvent.getLastIndex());
        boolean adjust = listSelectionEvent.getValueIsAdjusting();
        System.out.println(", Adjusting? " + adjust);
        if (!adjust) {
          JList list = (JList) listSelectionEvent.getSource();
          int selections[] = list.getSelectedIndices();
          Object selectedValues[] = list.getSelectedValues();
          for (int i = 0, n = selections.length; i < n; i++) {
            if (i == 0) {
              System.out.println("  Selections: ");
            }
            System.out.println(selections[i] + "/" + selectedValues[i] + " ");
          }
        }
      }
    };
    jlist.addListSelectionListener(listSelectionListener);
    frame.setSize(350, 200);
    frame.setVisible(true);
  }
}





JList: getSelectedValues()

  
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class MainClass {
  public static void main(final String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E" };
    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);
    ListSelectionListener listSelectionListener = new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent listSelectionEvent) {
        System.out.println("First index: " + listSelectionEvent.getFirstIndex());
        System.out.println(", Last index: " + listSelectionEvent.getLastIndex());
        boolean adjust = listSelectionEvent.getValueIsAdjusting();
        System.out.println(", Adjusting? " + adjust);
        if (!adjust) {
          JList list = (JList) listSelectionEvent.getSource();
          int selections[] = list.getSelectedIndices();
          Object selectedValues[] = list.getSelectedValues();
          for (int i = 0, n = selections.length; i < n; i++) {
            if (i == 0) {
              System.out.println("  Selections: ");
            }
            System.out.println(selections[i] + "/" + selectedValues[i] + " ");
          }
        }
      }
    };
    jlist.addListSelectionListener(listSelectionListener);
    frame.setSize(350, 200);
    frame.setVisible(true);
  }
}





JList.getSelectionBackground()

  
//
import java.awt.ruponent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.event.ListDataListener;
public class MainClass extends JFrame {
  MainClass(String s) {
    super(s);
    ListModel lm = new StaticListModel();
    JList list = new JList();
    list.setModel(lm);
    list.setCellRenderer(new MyCellRenderer());
    getContentPane().add(new JScrollPane(list));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
  public static void main(String[] s) {
    MainClass l = new MainClass("ListModel");
    l.pack();
    l.setVisible(true);
  }
  class MyCellRenderer extends JLabel implements ListCellRenderer {
    public Component getListCellRendererComponent(JList list, Object value, int index,
        boolean isSelected, boolean cellHasFocus) {
      Component c = null;
      if (value == null) {
        c = new JLabel("(null)");
      } else if (value instanceof Component) {
        c = (Component) value;
      } else {
        c = new JLabel(value.toString());
      }
      if (isSelected) {
        c.setBackground(list.getSelectionBackground());
        c.setForeground(list.getSelectionForeground());
      } else {
        c.setBackground(list.getBackground());
        c.setForeground(list.getForeground());
      }
      if (c instanceof JComponent) {
        ((JComponent) c).setOpaque(true);
      }
      return c;
    }
  }
  class StaticListModel implements ListModel {
    private final Object[] data = { "Hello", new Object(), new java.util.Date(),
        new JLabel("Hello world!"), this, };
    public Object getElementAt(int index) {
      return data[index];
    }
    public int getSize() {
      return data.length;
    }
    public void addListDataListener(ListDataListener ldl) {
    }
    public void removeListDataListener(ListDataListener ldl) {
    }
  }
}





JList: getSelectionForeground()

  
//
import java.awt.ruponent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.event.ListDataListener;
public class MainClass extends JFrame {
  MainClass(String s) {
    super(s);
    ListModel lm = new StaticListModel();
    JList list = new JList();
    list.setModel(lm);
    list.setCellRenderer(new MyCellRenderer());
    getContentPane().add(new JScrollPane(list));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
  public static void main(String[] s) {
    MainClass l = new MainClass("ListModel");
    l.pack();
    l.setVisible(true);
  }
  class MyCellRenderer extends JLabel implements ListCellRenderer {
    public Component getListCellRendererComponent(JList list, Object value, int index,
        boolean isSelected, boolean cellHasFocus) {
      Component c = null;
      if (value == null) {
        c = new JLabel("(null)");
      } else if (value instanceof Component) {
        c = (Component) value;
      } else {
        c = new JLabel(value.toString());
      }
      if (isSelected) {
        c.setBackground(list.getSelectionBackground());
        c.setForeground(list.getSelectionForeground());
      } else {
        c.setBackground(list.getBackground());
        c.setForeground(list.getForeground());
      }
      if (c instanceof JComponent) {
        ((JComponent) c).setOpaque(true);
      }
      return c;
    }
  }
  class StaticListModel implements ListModel {
    private final Object[] data = { "Hello", new Object(), new java.util.Date(),
        new JLabel("Hello world!"), this, };
    public Object getElementAt(int index) {
      return data[index];
    }
    public int getSize() {
      return data.length;
    }
    public void addListDataListener(ListDataListener ldl) {
    }
    public void removeListDataListener(ListDataListener ldl) {
    }
  }
}





JList: getVisibleRowCount()

  

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();
  }
}





JList: isSelectedIndex(int index)

  
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 index = 2;
    boolean isSel = list.isSelectedIndex(index);
  }
}





JList: isSelectionEmpty()

  
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);
    boolean anySelected = !list.isSelectionEmpty();
  }
}





JList: locationToIndex(Point p)

  
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 MainClass {
  public static void main(final String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E" };
    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);
    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);
  }
}





JList: removeSelectionInterval(int index0, int index1)

  
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 start = 0;
    int end = 0;
    list.removeSelectionInterval(start, end);
  }
}





JList: setCellRenderer(ListCellRenderer cellRenderer)

  
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Font;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
public class MainClass {
  public static void main(String args[]) throws Exception {
    Object elements[][] = { { new Font("Courier", Font.BOLD, 16), Color.YELLOW, "This" },
        { new Font("Helvetica", Font.ITALIC, 8), Color.DARK_GRAY, "Computer" } };
    JFrame frame = new JFrame("Complex Renderer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JList jlist = new JList(elements);
    ListCellRenderer renderer = new ComplexCellRenderer();
    jlist.setCellRenderer(renderer);
    JScrollPane scrollPane = new JScrollPane(jlist);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}
class ComplexCellRenderer implements ListCellRenderer {
  protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    Font theFont = null;
    Color theForeground = null;
    String theText = null;
    JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
        isSelected, cellHasFocus);
    if (value instanceof Object[]) {
      Object values[] = (Object[]) value;
      theFont = (Font) values[0];
      theForeground = (Color) values[1];
      theText = (String) values[2];
    } else {
      theFont = list.getFont();
      theForeground = list.getForeground();
      theText = "";
    }
    if (!isSelected) {
      renderer.setForeground(theForeground);
    }
    renderer.setText(theText);
    renderer.setFont(theFont);
    return renderer;
  }
}





JList: setDragEnabled(boolean b)

  
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class DragTest14 extends JFrame {
  JList jl;
  String[] items = { "Java", "C", "C++", "Lisp", "Perl", "Python" };
  public DragTest14() {
    super("Drag Test 1.4");
    setSize(200, 150);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    jl = new JList(items);
    jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jl.setDragEnabled(true);
    getContentPane().add(new JScrollPane(jl), BorderLayout.CENTER);
    setVisible(true);
  }
  public static void main(String args[]) {
    new DragTest14();
  }
}





JList: setFixedCellHeight(int height)

  
import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class MainClass {
  public static void main(final String args[]) {
    String labels[] = { "A", "B", "C", "D", "E" };
    JFrame frame = new JFrame("Sizing Samples");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DefaultListModel model = new DefaultListModel();
    model.ensureCapacity(1000);
    for (int i = 0; i < 100; i++) {
      for (int j = 0; j < 5; j++) {
        model.addElement(labels[j]);
      }
    }
    JList jlist2 = new JList(model);
    jlist2.setVisibleRowCount(4);
    jlist2.setFixedCellHeight(12);
    jlist2.setFixedCellWidth(200);
    JScrollPane scrollPane2 = new JScrollPane(jlist2);
    frame.add(scrollPane2, BorderLayout.CENTER);
    frame.setSize(300, 350);
    frame.setVisible(true);
  }
}





JList: setFixedCellWidth(int width)

  

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);
    // Set the item width
    int cellWidth = 200;
    list.setFixedCellWidth(cellWidth);
    // Set the item height
    int cellHeight = 18;
    list.setFixedCellHeight(cellHeight);
  }
}





JList: setLayoutOrientation(int ori)

  
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class MainClass {
  public static void main(final String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E" };
    JFrame frame = new JFrame("Multi-Columns");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JList columns = new JList(labels);
    columns.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    columns.setVisibleRowCount(3);
    JScrollPane sp = new JScrollPane(columns);
    frame.add(sp, BorderLayout.CENTER);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





JList: setModel(ListModel model)

  
//
import java.awt.ruponent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.event.ListDataListener;
public class MainClass extends JFrame {
  MainClass(String s) {
    super(s);
    ListModel lm = new StaticListModel();
    JList list = new JList();
    list.setModel(lm);
    list.setCellRenderer(new MyCellRenderer());
    getContentPane().add(new JScrollPane(list));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
  public static void main(String[] s) {
    MainClass l = new MainClass("ListModel");
    l.pack();
    l.setVisible(true);
  }
  class MyCellRenderer extends JLabel implements ListCellRenderer {
    public Component getListCellRendererComponent(JList list, Object value, int index,
        boolean isSelected, boolean cellHasFocus) {
      Component c = null;
      if (value == null) {
        c = new JLabel("(null)");
      } else if (value instanceof Component) {
        c = (Component) value;
      } else {
        c = new JLabel(value.toString());
      }
      if (isSelected) {
        c.setBackground(list.getSelectionBackground());
        c.setForeground(list.getSelectionForeground());
      } else {
        c.setBackground(list.getBackground());
        c.setForeground(list.getForeground());
      }
      if (c instanceof JComponent) {
        ((JComponent) c).setOpaque(true);
      }
      return c;
    }
  }
  class StaticListModel implements ListModel {
    private final Object[] data = { "Hello", new Object(), new java.util.Date(),
        new JLabel("Hello world!"), this, };
    public Object getElementAt(int index) {
      return data[index];
    }
    public int getSize() {
      return data.length;
    }
    public void addListDataListener(ListDataListener ldl) {
    }
    public void removeListDataListener(ListDataListener ldl) {
    }
  }
}





JList: setPrototypeCellValue(Object prototypeCellValue)

  
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 protoCellValue = "My Sample Item Value";
    list.setPrototypeCellValue(protoCellValue);
  }
}





JList: setSelectedIndex(int index)

  

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * ListDataEventDemo.java requires the Java Look and Feel Graphics
 * Repository (jlfgr-1_0.jar).  You can download this file from
 * http://java.sun.ru/developer/techDocs/hi/repository/
 * Put it in the class path using one of the following commands
 * (assuming jlfgr-1_0.jar is in a subdirectory named jars):
 *
 *   java -cp .;jars/jlfgr-1_0.jar ListDataEventDemo [Microsoft Windows]
 *   java -cp .:jars/jlfgr-1_0.jar ListDataEventDemo [UNIX]
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Main extends JPanel implements ListSelectionListener {
  private JList list;
  private DefaultListModel listModel;
  private static final String addString = "Add";
  private static final String deleteString = "Delete";
  private static final String upString = "Move up";
  private static final String downString = "Move down";
  private JButton addButton;
  private JButton deleteButton;
  private JButton upButton;
  private JButton downButton;
  private JTextField nameField;
  private JTextArea log;
  static private String newline = "\n";
  public Main() {
    super(new BorderLayout());
    // Create and populate the list model.
    listModel = new DefaultListModel();
    listModel.addElement("Whistler, Canada");
    listModel.addElement("Jackson Hole, Wyoming");
    listModel.addElement("Squaw Valley, California");
    listModel.addElement("Telluride, Colorado");
    listModel.addElement("Taos, New Mexico");
    listModel.addElement("Snowbird, Utah");
    listModel.addElement("Chamonix, France");
    listModel.addElement("Banff, Canada");
    listModel.addElement("Arapahoe Basin, Colorado");
    listModel.addElement("Kirkwood, California");
    listModel.addElement("Sun Valley, Idaho");
    listModel.addListDataListener(new MyListDataListener());
    // Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);
    JScrollPane listScrollPane = new JScrollPane(list);
    // Create the list-modifying buttons.
    addButton = new JButton(addString);
    addButton.setActionCommand(addString);
    addButton.addActionListener(new AddButtonListener());
    deleteButton = new JButton(deleteString);
    deleteButton.setActionCommand(deleteString);
    deleteButton.addActionListener(new DeleteButtonListener());
    ImageIcon icon = createImageIcon("Up16");
    if (icon != null) {
      upButton = new JButton(icon);
      upButton.setMargin(new Insets(0, 0, 0, 0));
    } else {
      upButton = new JButton("Move up");
    }
    upButton.setToolTipText("Move the currently selected list item higher.");
    upButton.setActionCommand(upString);
    upButton.addActionListener(new UpDownListener());
    icon = createImageIcon("Down16");
    if (icon != null) {
      downButton = new JButton(icon);
      downButton.setMargin(new Insets(0, 0, 0, 0));
    } else {
      downButton = new JButton("Move down");
    }
    downButton.setToolTipText("Move the currently selected list item lower.");
    downButton.setActionCommand(downString);
    downButton.addActionListener(new UpDownListener());
    JPanel upDownPanel = new JPanel(new GridLayout(2, 1));
    upDownPanel.add(upButton);
    upDownPanel.add(downButton);
    // Create the text field for entering new names.
    nameField = new JTextField(15);
    nameField.addActionListener(new AddButtonListener());
    String name = listModel.getElementAt(list.getSelectedIndex()).toString();
    nameField.setText(name);
    // Create a control panel, using the default FlowLayout.
    JPanel buttonPane = new JPanel();
    buttonPane.add(nameField);
    buttonPane.add(addButton);
    buttonPane.add(deleteButton);
    buttonPane.add(upDownPanel);
    // Create the log for reporting list data events.
    log = new JTextArea(10, 20);
    JScrollPane logScrollPane = new JScrollPane(log);
    // Create a split pane for the log and the list.
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
        listScrollPane, logScrollPane);
    splitPane.setResizeWeight(0.5);
    // Put everything together.
    add(buttonPane, BorderLayout.PAGE_START);
    add(splitPane, BorderLayout.CENTER);
  }
  class MyListDataListener implements ListDataListener {
    public void contentsChanged(ListDataEvent e) {
      log.append("contentsChanged: " + e.getIndex0() + ", " + e.getIndex1()
          + newline);
      log.setCaretPosition(log.getDocument().getLength());
    }
    public void intervalAdded(ListDataEvent e) {
      log.append("intervalAdded: " + e.getIndex0() + ", " + e.getIndex1()
          + newline);
      log.setCaretPosition(log.getDocument().getLength());
    }
    public void intervalRemoved(ListDataEvent e) {
      log.append("intervalRemoved: " + e.getIndex0() + ", " + e.getIndex1()
          + newline);
      log.setCaretPosition(log.getDocument().getLength());
    }
  }
  class DeleteButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      /*
       * This method can be called only if there"s a valid selection, so go
       * ahead and remove whatever"s selected.
       */
      ListSelectionModel lsm = list.getSelectionModel();
      int firstSelected = lsm.getMinSelectionIndex();
      int lastSelected = lsm.getMaxSelectionIndex();
      listModel.removeRange(firstSelected, lastSelected);
      int size = listModel.size();
      if (size == 0) {
        // List is empty: disable delete, up, and down buttons.
        deleteButton.setEnabled(false);
        upButton.setEnabled(false);
        downButton.setEnabled(false);
      } else {
        // Adjust the selection.
        if (firstSelected == listModel.getSize()) {
          // Removed item in last position.
          firstSelected--;
        }
        list.setSelectedIndex(firstSelected);
      }
    }
  }
  /** A listener shared by the text field and add button. */
  class AddButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      if (nameField.getText().equals("")) {
        // User didn"t type in a name...
        Toolkit.getDefaultToolkit().beep();
        return;
      }
      int index = list.getSelectedIndex();
      int size = listModel.getSize();
      // If no selection or if item in last position is selected,
      // add the new one to end of list, and select new one.
      if (index == -1 || (index + 1 == size)) {
        listModel.addElement(nameField.getText());
        list.setSelectedIndex(size);
        // Otherwise insert the new one after the current selection,
        // and select new one.
      } else {
        listModel.insertElementAt(nameField.getText(), index + 1);
        list.setSelectedIndex(index + 1);
      }
    }
  }
  // Listen for clicks on the up and down arrow buttons.
  class UpDownListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      // This method can be called only when
      // there"s a valid selection,
      // so go ahead and move the list item.
      int moveMe = list.getSelectedIndex();
      if (e.getActionCommand().equals(upString)) {
        // UP ARROW BUTTON
        if (moveMe != 0) {
          // not already at top
          swap(moveMe, moveMe - 1);
          list.setSelectedIndex(moveMe - 1);
          list.ensureIndexIsVisible(moveMe - 1);
        }
      } else {
        // DOWN ARROW BUTTON
        if (moveMe != listModel.getSize() - 1) {
          // not already at bottom
          swap(moveMe, moveMe + 1);
          list.setSelectedIndex(moveMe + 1);
          list.ensureIndexIsVisible(moveMe + 1);
        }
      }
    }
  }
  // Swap two elements in the list.
  private void swap(int a, int b) {
    Object aObject = listModel.getElementAt(a);
    Object bObject = listModel.getElementAt(b);
    listModel.set(a, bObject);
    listModel.set(b, aObject);
  }
  // Listener method for list selection changes.
  public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting() == false) {
      if (list.getSelectedIndex() == -1) {
        // No selection: disable delete, up, and down buttons.
        deleteButton.setEnabled(false);
        upButton.setEnabled(false);
        downButton.setEnabled(false);
        nameField.setText("");
      } else if (list.getSelectedIndices().length > 1) {
        // Multiple selection: disable up and down buttons.
        deleteButton.setEnabled(true);
        upButton.setEnabled(false);
        downButton.setEnabled(false);
      } else {
        // Single selection: permit all operations.
        deleteButton.setEnabled(true);
        upButton.setEnabled(true);
        downButton.setEnabled(true);
        nameField.setText(list.getSelectedValue().toString());
      }
    }
  }
  /** Returns an ImageIcon, or null if the path was invalid. */
  protected static ImageIcon createImageIcon(String imageName) {
    String imgLocation = "toolbarButtonGraphics/navigation/" + imageName
        + ".gif";
    java.net.URL imageURL = Main.class.getResource(imgLocation);
    if (imageURL == null) {
      System.err.println("Resource not found: " + imgLocation);
      return null;
    } else {
      return new ImageIcon(imageURL);
    }
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("ListDataEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    JComponent newContentPane = new Main();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Don"t let the content pane get too small.
    // (Works if the Java look and feel provides
    // the window decorations.)
    newContentPane.setMinimumSize(new Dimension(newContentPane
        .getPreferredSize().width, 100));
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}





JList: setSelectedValue(Object anObject, boolean shouldScroll)

  
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);
    boolean scrollIntoView = true;
    list.setSelectedValue("B", scrollIntoView);
  }
}





JList: setSelectionInterval(int anchor, int lead)

  
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);
    // Select the second item
    int start = 1;
    int end = 1;
    list.setSelectionInterval(start, end);
  }
}





JList: setSelectionMode(int selectionMode)

  

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * ListDataEventDemo.java requires the Java Look and Feel Graphics
 * Repository (jlfgr-1_0.jar).  You can download this file from
 * http://java.sun.ru/developer/techDocs/hi/repository/
 * Put it in the class path using one of the following commands
 * (assuming jlfgr-1_0.jar is in a subdirectory named jars):
 *
 *   java -cp .;jars/jlfgr-1_0.jar ListDataEventDemo [Microsoft Windows]
 *   java -cp .:jars/jlfgr-1_0.jar ListDataEventDemo [UNIX]
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Main extends JPanel implements ListSelectionListener {
  private JList list;
  private DefaultListModel listModel;
  private static final String addString = "Add";
  private static final String deleteString = "Delete";
  private static final String upString = "Move up";
  private static final String downString = "Move down";
  private JButton addButton;
  private JButton deleteButton;
  private JButton upButton;
  private JButton downButton;
  private JTextField nameField;
  private JTextArea log;
  static private String newline = "\n";
  public Main() {
    super(new BorderLayout());
    // Create and populate the list model.
    listModel = new DefaultListModel();
    listModel.addElement("Whistler, Canada");
    listModel.addElement("Jackson Hole, Wyoming");
    listModel.addElement("Squaw Valley, California");
    listModel.addElement("Telluride, Colorado");
    listModel.addElement("Taos, New Mexico");
    listModel.addElement("Snowbird, Utah");
    listModel.addElement("Chamonix, France");
    listModel.addElement("Banff, Canada");
    listModel.addElement("Arapahoe Basin, Colorado");
    listModel.addElement("Kirkwood, California");
    listModel.addElement("Sun Valley, Idaho");
    listModel.addListDataListener(new MyListDataListener());
    // Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);
    JScrollPane listScrollPane = new JScrollPane(list);
    // Create the list-modifying buttons.
    addButton = new JButton(addString);
    addButton.setActionCommand(addString);
    addButton.addActionListener(new AddButtonListener());
    deleteButton = new JButton(deleteString);
    deleteButton.setActionCommand(deleteString);
    deleteButton.addActionListener(new DeleteButtonListener());
    ImageIcon icon = createImageIcon("Up16");
    if (icon != null) {
      upButton = new JButton(icon);
      upButton.setMargin(new Insets(0, 0, 0, 0));
    } else {
      upButton = new JButton("Move up");
    }
    upButton.setToolTipText("Move the currently selected list item higher.");
    upButton.setActionCommand(upString);
    upButton.addActionListener(new UpDownListener());
    icon = createImageIcon("Down16");
    if (icon != null) {
      downButton = new JButton(icon);
      downButton.setMargin(new Insets(0, 0, 0, 0));
    } else {
      downButton = new JButton("Move down");
    }
    downButton.setToolTipText("Move the currently selected list item lower.");
    downButton.setActionCommand(downString);
    downButton.addActionListener(new UpDownListener());
    JPanel upDownPanel = new JPanel(new GridLayout(2, 1));
    upDownPanel.add(upButton);
    upDownPanel.add(downButton);
    // Create the text field for entering new names.
    nameField = new JTextField(15);
    nameField.addActionListener(new AddButtonListener());
    String name = listModel.getElementAt(list.getSelectedIndex()).toString();
    nameField.setText(name);
    // Create a control panel, using the default FlowLayout.
    JPanel buttonPane = new JPanel();
    buttonPane.add(nameField);
    buttonPane.add(addButton);
    buttonPane.add(deleteButton);
    buttonPane.add(upDownPanel);
    // Create the log for reporting list data events.
    log = new JTextArea(10, 20);
    JScrollPane logScrollPane = new JScrollPane(log);
    // Create a split pane for the log and the list.
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
        listScrollPane, logScrollPane);
    splitPane.setResizeWeight(0.5);
    // Put everything together.
    add(buttonPane, BorderLayout.PAGE_START);
    add(splitPane, BorderLayout.CENTER);
  }
  class MyListDataListener implements ListDataListener {
    public void contentsChanged(ListDataEvent e) {
      log.append("contentsChanged: " + e.getIndex0() + ", " + e.getIndex1()
          + newline);
      log.setCaretPosition(log.getDocument().getLength());
    }
    public void intervalAdded(ListDataEvent e) {
      log.append("intervalAdded: " + e.getIndex0() + ", " + e.getIndex1()
          + newline);
      log.setCaretPosition(log.getDocument().getLength());
    }
    public void intervalRemoved(ListDataEvent e) {
      log.append("intervalRemoved: " + e.getIndex0() + ", " + e.getIndex1()
          + newline);
      log.setCaretPosition(log.getDocument().getLength());
    }
  }
  class DeleteButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      /*
       * This method can be called only if there"s a valid selection, so go
       * ahead and remove whatever"s selected.
       */
      ListSelectionModel lsm = list.getSelectionModel();
      int firstSelected = lsm.getMinSelectionIndex();
      int lastSelected = lsm.getMaxSelectionIndex();
      listModel.removeRange(firstSelected, lastSelected);
      int size = listModel.size();
      if (size == 0) {
        // List is empty: disable delete, up, and down buttons.
        deleteButton.setEnabled(false);
        upButton.setEnabled(false);
        downButton.setEnabled(false);
      } else {
        // Adjust the selection.
        if (firstSelected == listModel.getSize()) {
          // Removed item in last position.
          firstSelected--;
        }
        list.setSelectedIndex(firstSelected);
      }
    }
  }
  /** A listener shared by the text field and add button. */
  class AddButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      if (nameField.getText().equals("")) {
        // User didn"t type in a name...
        Toolkit.getDefaultToolkit().beep();
        return;
      }
      int index = list.getSelectedIndex();
      int size = listModel.getSize();
      // If no selection or if item in last position is selected,
      // add the new one to end of list, and select new one.
      if (index == -1 || (index + 1 == size)) {
        listModel.addElement(nameField.getText());
        list.setSelectedIndex(size);
        // Otherwise insert the new one after the current selection,
        // and select new one.
      } else {
        listModel.insertElementAt(nameField.getText(), index + 1);
        list.setSelectedIndex(index + 1);
      }
    }
  }
  // Listen for clicks on the up and down arrow buttons.
  class UpDownListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      // This method can be called only when
      // there"s a valid selection,
      // so go ahead and move the list item.
      int moveMe = list.getSelectedIndex();
      if (e.getActionCommand().equals(upString)) {
        // UP ARROW BUTTON
        if (moveMe != 0) {
          // not already at top
          swap(moveMe, moveMe - 1);
          list.setSelectedIndex(moveMe - 1);
          list.ensureIndexIsVisible(moveMe - 1);
        }
      } else {
        // DOWN ARROW BUTTON
        if (moveMe != listModel.getSize() - 1) {
          // not already at bottom
          swap(moveMe, moveMe + 1);
          list.setSelectedIndex(moveMe + 1);
          list.ensureIndexIsVisible(moveMe + 1);
        }
      }
    }
  }
  // Swap two elements in the list.
  private void swap(int a, int b) {
    Object aObject = listModel.getElementAt(a);
    Object bObject = listModel.getElementAt(b);
    listModel.set(a, bObject);
    listModel.set(b, aObject);
  }
  // Listener method for list selection changes.
  public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting() == false) {
      if (list.getSelectedIndex() == -1) {
        // No selection: disable delete, up, and down buttons.
        deleteButton.setEnabled(false);
        upButton.setEnabled(false);
        downButton.setEnabled(false);
        nameField.setText("");
      } else if (list.getSelectedIndices().length > 1) {
        // Multiple selection: disable up and down buttons.
        deleteButton.setEnabled(true);
        upButton.setEnabled(false);
        downButton.setEnabled(false);
      } else {
        // Single selection: permit all operations.
        deleteButton.setEnabled(true);
        upButton.setEnabled(true);
        downButton.setEnabled(true);
        nameField.setText(list.getSelectedValue().toString());
      }
    }
  }
  /** Returns an ImageIcon, or null if the path was invalid. */
  protected static ImageIcon createImageIcon(String imageName) {
    String imgLocation = "toolbarButtonGraphics/navigation/" + imageName
        + ".gif";
    java.net.URL imageURL = Main.class.getResource(imgLocation);
    if (imageURL == null) {
      System.err.println("Resource not found: " + imgLocation);
      return null;
    } else {
      return new ImageIcon(imageURL);
    }
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("ListDataEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    JComponent newContentPane = new Main();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Don"t let the content pane get too small.
    // (Works if the Java look and feel provides
    // the window decorations.)
    newContentPane.setMinimumSize(new Dimension(newContentPane
        .getPreferredSize().width, 100));
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}





JList: setVisibleRowCount(int count)

  
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class MainClass {
  public static void main(final String args[]) {
    String labels[] = { "A", "B", "C", "D", "E" };
    JFrame frame = new JFrame("Sizing Samples");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JList jlist1 = new JList(labels);
    jlist1.setVisibleRowCount(4);
    JScrollPane scrollPane1 = new JScrollPane(jlist1);
    frame.add(scrollPane1, BorderLayout.NORTH);
  
    frame.setSize(300, 350);
    frame.setVisible(true);
  }
}





JList.VERTICAL_WRAP

  
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);
    // Change orientation to top-to-bottom, left-to-right layout
    list.setLayoutOrientation(JList.VERTICAL_WRAP);
  }
}





new JList(ListModel dataModel) (Share model with JComboBox)

  
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 MainClass {
  public static void main(final String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E" };
    final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);
    JFrame frame = new JFrame("Shared Data");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JComboBox comboBox1 = new JComboBox(model);
    comboBox1.setMaximumRowCount(5);
    comboBox1.setEditable(true);
    frame.add(comboBox1, 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("a");
      }
    };
    button.addActionListener(actionListener);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





new JList(Object[] listData)

  
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class MainClass {
  public static void main(final String args[]) {
    String labels[] = { "A", "B", "C", "D", "E" };
    JFrame frame = new JFrame("Selection Modes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JList list1 = new JList(labels);
    JScrollPane sp1 = new JScrollPane(list1);
    sp1.setColumnHeaderView(new JLabel("List"));
    frame.add(sp1, BorderLayout.CENTER);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





new JList(Vector<?> listData)

  
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class Main {
  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);
  }
}





new JScrollPane(JList list)

  
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class MainClass extends JFrame {
  JScrollPane scrollpane;
  public MainClass() {
    super("JScrollPane Demonstration");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    String categories[] = { "A", "B", "C", "D", "E", "F" };
    JList list = new JList(categories);
    scrollpane = new JScrollPane(list);
    getContentPane().add(scrollpane, BorderLayout.CENTER);
  }
  public static void main(String args[]) {
    MainClass sl = new MainClass();
    sl.setVisible(true);
  }
}