Java/Swing JFC/List

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

Содержание

Add another selection - the third item

   <source lang="java">

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

}

</source>
   
  
 
  



Adding and Removing an Item in a JList Component

   <source lang="java">

import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {

 public static void main(String[] argv) throws Exception {
   DefaultListModel model = new DefaultListModel();
   JList list = new JList(model);
   // Initialize the list with items
   String[] items = { "A", "B", "C", "D" };
   for (int i = 0; i < items.length; i++) {
     model.add(i, items[i]);
   }
 }

}

</source>
   
  
 
  



Add JList to Scroll pane

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; public class ListSample {

 public static void main(String args[]) {
   String labels[] = { "A", "B", "C", "D","E", "F", "G", "H","I", "J" };
   String title = "JList Sample";
   JFrame f = new JFrame(title);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JList list = new JList(labels);
   JScrollPane scrollPane = new JScrollPane(list);
   Container contentPane = f.getContentPane();
   contentPane.add(scrollPane, BorderLayout.CENTER);
   f.setSize(200, 200);
   f.setVisible(true);
 }

}

      </source>
   
  
 
  



A default button model

   <source lang="java">

import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonModel; import javax.swing.DefaultButtonModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; public class Main {

 public static void main(String[] args) {
   final JButton ok = new JButton("ok");
   JCheckBox cb = new JCheckBox("Enabled", true);
   cb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (ok.isEnabled())
         ok.setEnabled(false);
       else
         ok.setEnabled(true);
     }
   });
   ButtonModel model = new DefaultButtonModel() {
     public void setEnabled(boolean b) {
       if (b)
         System.out.println("Pressed: true");
       else
         System.out.println("Pressed: false");
       super.setEnabled(b);
     }
     public void setArmed(boolean b) {
       if (b)
         System.out.println("Armed: true");
       else
         System.out.println("Armed: false");
       super.setArmed(b);
     }
     public void setPressed(boolean b) {
       if (b)
         System.out.println("Pressed: true");
       else
         System.out.println("Pressed: false");
       super.setPressed(b);
     }
   };
   ok.setModel(model);
   JFrame f = new JFrame();
   f.setLayout(new FlowLayout());
   f.add(ok);
   f.add(cb);
   f.setSize(350, 250);
   f.setLocationRelativeTo(null);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}

</source>
   
  
 
  



A graphical list selection monitor

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// SelectionMonitor.java //A graphical list selection monitor. // import java.awt.BorderLayout; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class SelectionMonitor extends JPanel {

 String label[] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six",
     "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve" };
 JCheckBox checks[] = new JCheckBox[label.length];
 JList list;
 public SelectionMonitor() {
   setLayout(new BorderLayout());
   list = new JList(label);
   JScrollPane pane = new JScrollPane(list);
   //  Format the list and the buttons in a vertical box
   Box rightBox = new Box(BoxLayout.Y_AXIS);
   Box leftBox = new Box(BoxLayout.Y_AXIS);
   //  Monitor all list selections
   list.addListSelectionListener(new RadioUpdater());
   for (int i = 0; i < label.length; i++) {
     checks[i] = new JCheckBox("Selection " + i);
     checks[i].setEnabled(false);
     rightBox.add(checks[i]);
   }
   leftBox.add(pane);
   add(rightBox, BorderLayout.EAST);
   add(leftBox, BorderLayout.WEST);
 }
 public static void main(String s[]) {
   JFrame frame = new JFrame("Selection Monitor");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(new SelectionMonitor());
   frame.pack();
   frame.setVisible(true);
 }
 // Inner class that responds to selection events to update the buttons
 class RadioUpdater implements ListSelectionListener {
   public void valueChanged(ListSelectionEvent e) {
     //  If either of these are true, the event can be ignored.
     if ((!e.getValueIsAdjusting()) || (e.getFirstIndex() == -1))
       return;
     //  Change the radio button to match the current selection state
     //  for each list item that reported a change.
     for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) {
       checks[i].setSelected(((JList) e.getSource())
           .isSelectedIndex(i));
     }
   }
 }

}

      </source>
   
  
 
  



A JTextArea is a multi-line text area that displays plain text.

   <source lang="java">

import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class TextArea {

 public static void main(String[] args) {
   JFrame f = new JFrame();
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTextArea area = new JTextArea();
   area.setLineWrap(true);
   area.setWrapStyleWord(true);
   area.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
   f.add(new JScrollPane(area));
   f.setSize(new Dimension(350, 300));
   f.setLocationRelativeTo(null);
   f.setVisible(true);
 }

}

</source>
   
  
 
  



An example of JList with a DefaultListModel

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// ListModelExample.java //An example of JList with a DefaultListModel that we build up at runtime. // 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.JPanel; import javax.swing.JScrollPane; public class ListModelExample extends JPanel {

 JList list;
 DefaultListModel model;
 int counter = 15;
 public ListModelExample() {
   setLayout(new BorderLayout());
   model = new DefaultListModel();
   list = new JList(model);
   JScrollPane pane = new JScrollPane(list);
   JButton addButton = new JButton("Add Element");
   JButton removeButton = new JButton("Remove Element");
   for (int i = 0; i < 15; i++)
     model.addElement("Element " + i);
   addButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       model.addElement("Element " + counter);
       counter++;
     }
   });
   removeButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (model.getSize() > 0)
         model.removeElementAt(0);
     }
   });
   add(pane, BorderLayout.NORTH);
   add(addButton, BorderLayout.WEST);
   add(removeButton, BorderLayout.EAST);
 }
 public static void main(String s[]) {
   JFrame frame = new JFrame("List Model Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(new ListModelExample());
   frame.setSize(260, 200);
   frame.setVisible(true);
 }

}

      </source>
   
  
 
  



Append an item

   <source lang="java">

import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {

 public static void main(String[] argv) throws Exception {
   // Create a list that allows adds and removes
   DefaultListModel model = new DefaultListModel();
   JList list = new JList(model);
   int pos = list.getModel().getSize();
   model.add(pos, "E");
 }

}

</source>
   
  
 
  



Arranging Items in a JList Component

   <source lang="java">

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

}

</source>
   
  
 
  



ArrayList with a ListModel for ease of use

   <source lang="java">

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.util.ArrayList; import java.util.Collection; import javax.swing.ListModel; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; /**

* FilterGUIListModel combines an ArrayList with a ListModel for ease of use.
*/

public class FilterGUIListModel extends ArrayList implements ListModel {

 protected Object source;
 FilterGUIListModel(Object src) {
   source = src;
 }
 public Object getElementAt(int index) {
   return get(index);
 }
 public int getSize() {
   return size();
 }
 ArrayList listeners = new ArrayList();
 public void removeListDataListener(javax.swing.event.ListDataListener l) {
   listeners.remove(l);
 }
 public void addListDataListener(javax.swing.event.ListDataListener l) {
   listeners.add(l);
 }
 void notifyListeners() {
   // no attempt at optimziation
   ListDataEvent le = new ListDataEvent(source,
       ListDataEvent.CONTENTS_CHANGED, 0, getSize());
   for (int i = 0; i < listeners.size(); i++) {
     ((ListDataListener) listeners.get(i)).contentsChanged(le);
   }
 }
 // REMAINDER ARE OVERRIDES JUST TO CALL NOTIFYLISTENERS
 public boolean add(Object o) {
   boolean b = super.add(o);
   if (b)
     notifyListeners();
   return b;
 }
 public void add(int index, Object element) {
   super.add(index, element);
   notifyListeners();
 }
 public boolean addAll(Collection o) {
   boolean b = super.add(o);
   if (b)
     notifyListeners();
   return b;
 }
 public void clear() {
   super.clear();
   notifyListeners();
 }
 public Object remove(int i) {
   Object o = super.remove(i);
   notifyListeners();
   return o;
 }
 public boolean remove(Object o) {
   boolean b = super.remove(o);
   if (b)
     notifyListeners();
   return b;
 }
 public Object set(int index, Object element) {
   Object o = super.set(index, element);
   notifyListeners();
   return o;
 }

}

      </source>
   
  
 
  



A single-selection JList.

   <source lang="java">

import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class Main {

 String languages[] = { "Java", "Perl", "Python", "C++", "Basic", "C#" };
 JList jlst = new JList(languages);
 Main() {
   JFrame jfrm = new JFrame("Use JList");
   jfrm.setLayout(new FlowLayout());
   jfrm.setSize(200, 160);
   jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   jlst.addListSelectionListener(new ListSelectionListener() {
     public void valueChanged(ListSelectionEvent le) {
       int idx = jlst.getSelectedIndex();
       if (idx != -1)
         System.out.println("Current selection: " + languages[idx]);
       else
         System.out.println("Please choose a language.");
     }
   });
   jfrm.add(new JScrollPane(jlst));
   jfrm.setSize(300, 300);
   jfrm.setVisible(true);
 }
 public static void main(String args[]) {
   new Main();
 }

}

</source>
   
  
 
  



A spinner that rolls from the end of a list to beginning

   <source lang="java">

import java.util.List; import javax.swing.SpinnerListModel; public class RolloverSpinnerListModel extends SpinnerListModel {

 public RolloverSpinnerListModel(Object[] items) {
   super(items);
 }
 public RolloverSpinnerListModel(List items) {
   super(items);
 }
 public Object getNextValue() {
   Object nv = super.getNextValue();
   if (nv != null) {
     return nv;
   }
   return getList().get(0);
 }
 public Object getPreviousValue() {
   Object pv = super.getPreviousValue();
   if (pv != null) {
     return pv;
   }
   List l = getList();
   return l.get(l.size() - 1);
 }

}

</source>
   
  
 
  



changes the layout orientation so that its items are displayed top-to-bottom and left-to-right.

   <source lang="java">

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

}

</source>
   
  
 
  



Clear all selections

   <source lang="java">

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

}

</source>
   
  
 
  



Construct the list component

   <source lang="java">

import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; public class SimpleList extends JFrame {

 protected JList list;
 public SimpleList() {
   super("Simple Swing List");
   setSize(500, 240);
   String[] item = { "First", "Second", "Third" };
   list = new JList(item);
   JScrollPane scrollPane = new JScrollPane();
   scrollPane.getViewport().add(list);
   getContentPane().add(scrollPane, BorderLayout.CENTER);
   WindowListener exit = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   };
   addWindowListener(exit);
   setVisible(true);
 }
 public static void main(String argv[]) {
   new SimpleList();
 }

}

      </source>
   
  
 
  



Create a list that allows adds and removes

   <source lang="java">

import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {

 public static void main(String[] argv) throws Exception {
   DefaultListModel model = new DefaultListModel();
   JList list = new JList(model);
   int pos = 0;
   model.add(pos, "a");
 }

}

</source>
   
  
 
  



Create JList from array of string value

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// SimpleList2.java //A variation on SimpleList. This version modifies the selecion model used. // import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultListSelectionModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class SimpleList2 extends JPanel {

 String label[] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six",
     "Seven", "Eight", "Nine", "Ten", "Eleven" };
 JList list;
 public SimpleList2() {
   setLayout(new BorderLayout());
   list = new JList(label);
   JButton button = new JButton("Print");
   JScrollPane pane = new JScrollPane(list);
   DefaultListSelectionModel m = new DefaultListSelectionModel();
   m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   m.setLeadAnchorNotificationEnabled(false);
   list.setSelectionModel(m);
   list.addListSelectionListener(new ListSelectionListener() {
     public void valueChanged(ListSelectionEvent e) {
       System.out.println(e.toString());
     }
   });
   button.addActionListener(new PrintListener());
   add(pane, BorderLayout.NORTH);
   add(button, BorderLayout.SOUTH);
 }
 public static void main(String s[]) {
   JFrame frame = new JFrame("List Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(new SimpleList2());
   frame.pack();
   frame.setVisible(true);
 }
 // An inner class to respond to clicks on the Print button
 class PrintListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     int selected[] = list.getSelectedIndices();
     System.out.println("Selected Elements:  ");
     for (int i = 0; i < selected.length; i++) {
       String element = (String) list.getModel().getElementAt(
           selected[i]);
       System.out.println("  " + element);
     }
   }
 }

}

      </source>
   
  
 
  



Create list from list model

   <source lang="java">

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; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class LongListTest extends JFrame implements ListSelectionListener {

 JLabel label = new JLabel();
 public LongListTest() {
   setTitle("LongListTest");
   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);
   wordList.setFixedCellWidth(50);
   wordList.setFixedCellHeight(15);
   JScrollPane scrollPane = new JScrollPane(wordList);
   JPanel p = new JPanel();
   p.add(scrollPane);
   wordList.addListSelectionListener(this);
   getContentPane().add(p, "Center");
   getContentPane().add(label, "North");
 }
 public void valueChanged(ListSelectionEvent evt) {
   JList source = (JList) evt.getSource();
   String word = (String) source.getSelectedValue();
   label.setText(word);
 }
 public static void main(String[] args) {
   JFrame frame = new LongListTest();
   frame.show();
 }

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

}

      </source>
   
  
 
  



Creating a JList Component

   <source lang="java">

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

}

</source>
   
  
 
  



Demonstrate Swing JList ListModel

   <source lang="java">

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.awt.BorderLayout; import java.awt.ruponent; import java.awt.Container; import java.awt.FlowLayout; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /**

* Demonstrate Swing "JList" ListModel
* 
* @author Ian Darwin
* @author Tweaked by Jonathan Fuerth of SQLPower.ca
*/

public class JListModelDemo extends JListDemo {

 JListModelDemo(String s) {
   super(s);
   ListModel lm = new StaticListModel();
   list.setModel(lm);
   list.setCellRenderer(new MyCellRenderer());
   setDefaultCloseOperation(EXIT_ON_CLOSE);
 }
 public static void main(String[] s) {
   JListModelDemo l = new JListModelDemo("ListModel");
   l.pack();
   l.setVisible(true);
 }
 class MyCellRenderer extends JLabel implements ListCellRenderer {
   /*
    * Get the Renderer for a given List Cell. This is the only method
    * defined by ListCellRenderer. If the object is already a component,
    * keep it, else toString it and wrap it in a JLabel. Reconfigure the
    * Component each time we"re called to accord for whether it"s selected
    * or not.
    */
   public Component getListCellRendererComponent(JList list, Object value, // value
                                       // to
                                       // display
       int index, // cell index
       boolean isSelected, // is the cell selected
       boolean cellHasFocus) // the list and the cell have the focus
   {
     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) {
     // since the list never changes, we don"t need this :-)
   }
   public void removeListDataListener(ListDataListener ldl) {
     // since the list never changes, we don"t need this :-)
   }
 }

} class JListDemo extends JFrame {

 JList list = null;
 JListDemo(String s) {
   super(s);
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   ArrayList data = new ArrayList();
   data.add("Hi");
   data.add("Hello");
   data.add("Goodbye");
   data.add("Adieu");
   data.add("Adios");
   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(list, BorderLayout.CENTER);
 }
 public static void main(String[] s) {
   JListDemo l = new JListDemo("Greetings");
   l.pack();
   l.setVisible(true);
 }

}

      </source>
   
  
 
  



Demonstrate Swing ScrollingList

   <source lang="java">

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

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.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /**

* Demonstrate Swing ScrollingList.
*/

public class JListDemo extends JFrame {

 JList list = null;
 JListDemo(String s) {
   super(s);
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   ArrayList data = new ArrayList();
   data.add("Hi");
   data.add("Hello");
   data.add("Goodbye");
   data.add("Adieu");
   data.add("Adios");
   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(list, BorderLayout.CENTER);
 }
 public static void main(String[] s) {
   JListDemo l = new JListDemo("Greetings");
   l.pack();
   l.setVisible(true);
 }

}

      </source>
   
  
 
  



Deselect the first item

   <source lang="java">

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

}

</source>
   
  
 
  



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

   <source lang="java">

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

}

</source>
   
  
 
  



Determine if there are any selected items

   <source lang="java">

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

}

</source>
   
  
 
  



Determine if the third item is selected

   <source lang="java">

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

}

</source>
   
  
 
  



Determining the Selected JRadioButton in a Button Group

   <source lang="java">

import java.util.Enumeration; import javax.swing.ButtonGroup; import javax.swing.JRadioButton; public class Main {

 public static void main(String[] argv) throws Exception {
 }
 public static JRadioButton getSelection(ButtonGroup group) {
   for (Enumeration e = group.getElements(); e.hasMoreElements();) {
     JRadioButton b = (JRadioButton) e.nextElement();
     if (b.getModel() == group.getSelection()) {
       return b;
     }
   }
   return null;
 }

}

</source>
   
  
 
  



Drag and Drop:JList and List

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// DragTest.java //A simple (?) test of the DragSource classes to see if we //can create a draggable object in a Java application. This version //works with 1.3 and higher SDKs. // import java.awt.BorderLayout; import java.awt.datatransfer.StringSelection; 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 java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; public class DragTest extends JFrame implements DragSourceListener,

   DragGestureListener {
 DragSource ds;
 JList jl;
 StringSelection transferable;
 String[] items = { "Java", "C", "C++", "Lisp", "Perl", "Python" };
 public DragTest() {
   super("Drag Test");
   setSize(200, 150);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent we) {
       System.exit(0);
     }
   });
   jl = new JList(items);
   jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   getContentPane().add(new JScrollPane(jl), BorderLayout.CENTER);
   ds = new DragSource();
   DragGestureRecognizer dgr = ds.createDefaultDragGestureRecognizer(jl,
       DnDConstants.ACTION_COPY, this);
   setVisible(true);
 }
 public void dragGestureRecognized(DragGestureEvent dge) {
   System.out.println("Drag Gesture Recognized!");
   transferable = new StringSelection(jl.getSelectedValue().toString());
   ds.startDrag(dge, DragSource.DefaultCopyDrop, transferable, this);
 }
 public void dragEnter(DragSourceDragEvent dsde) {
   System.out.println("Drag Enter");
 }
 public void dragExit(DragSourceEvent dse) {
   System.out.println("Drag Exit");
 }
 public void dragOver(DragSourceDragEvent dsde) {
   System.out.println("Drag Over");
 }
 public void dragDropEnd(DragSourceDropEvent dsde) {
   System.out.print("Drag Drop End: ");
   if (dsde.getDropSuccess()) {
     System.out.println("Succeeded");
   } else {
     System.out.println("Failed");
   }
 }
 public void dropActionChanged(DragSourceDragEvent dsde) {
   System.out.println("Drop Action Changed");
 }
 public static void main(String args[]) {
   new DragTest();
 }

}

      </source>
   
  
 
  



Dual JList with buttons in between

   <source lang="java">

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.AbstractListModel; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListModel; public class DualListBox extends JPanel {

 private static final Insets EMPTY_INSETS = new Insets(0, 0, 0, 0);
 private static final String ADD_BUTTON_LABEL = "Add >>";
 private static final String REMOVE_BUTTON_LABEL = "<< Remove";
 private static final String DEFAULT_SOURCE_CHOICE_LABEL = "Available Choices";
 private static final String DEFAULT_DEST_CHOICE_LABEL = "Your Choices";
 private JLabel sourceLabel;
 private JList sourceList;
 private SortedListModel sourceListModel;
 private JList destList;
 private SortedListModel destListModel;
 private JLabel destLabel;
 private JButton addButton;
 private JButton removeButton;
 public DualListBox() {
   initScreen();
 }
 public String getSourceChoicesTitle() {
   return sourceLabel.getText();
 }
 public void setSourceChoicesTitle(String newValue) {
   sourceLabel.setText(newValue);
 }
 public String getDestinationChoicesTitle() {
   return destLabel.getText();
 }
 public void setDestinationChoicesTitle(String newValue) {
   destLabel.setText(newValue);
 }
 public void clearSourceListModel() {
   sourceListModel.clear();
 }
 public void clearDestinationListModel() {
   destListModel.clear();
 }
 public void addSourceElements(ListModel newValue) {
   fillListModel(sourceListModel, newValue);
 }
 public void setSourceElements(ListModel newValue) {
   clearSourceListModel();
   addSourceElements(newValue);
 }
 public void addDestinationElements(ListModel newValue) {
   fillListModel(destListModel, newValue);
 }
 private void fillListModel(SortedListModel model, ListModel newValues) {
   int size = newValues.getSize();
   for (int i = 0; i < size; i++) {
     model.add(newValues.getElementAt(i));
   }
 }
 public void addSourceElements(Object newValue[]) {
   fillListModel(sourceListModel, newValue);
 }
 public void setSourceElements(Object newValue[]) {
   clearSourceListModel();
   addSourceElements(newValue);
 }
 public void addDestinationElements(Object newValue[]) {
   fillListModel(destListModel, newValue);
 }
 private void fillListModel(SortedListModel model, Object newValues[]) {
   model.addAll(newValues);
 }
 public Iterator sourceIterator() {
   return sourceListModel.iterator();
 }
 public Iterator destinationIterator() {
   return destListModel.iterator();
 }
 public void setSourceCellRenderer(ListCellRenderer newValue) {
   sourceList.setCellRenderer(newValue);
 }
 public ListCellRenderer getSourceCellRenderer() {
   return sourceList.getCellRenderer();
 }
 public void setDestinationCellRenderer(ListCellRenderer newValue) {
   destList.setCellRenderer(newValue);
 }
 public ListCellRenderer getDestinationCellRenderer() {
   return destList.getCellRenderer();
 }
 public void setVisibleRowCount(int newValue) {
   sourceList.setVisibleRowCount(newValue);
   destList.setVisibleRowCount(newValue);
 }
 public int getVisibleRowCount() {
   return sourceList.getVisibleRowCount();
 }
 public void setSelectionBackground(Color newValue) {
   sourceList.setSelectionBackground(newValue);
   destList.setSelectionBackground(newValue);
 }
 public Color getSelectionBackground() {
   return sourceList.getSelectionBackground();
 }
 public void setSelectionForeground(Color newValue) {
   sourceList.setSelectionForeground(newValue);
   destList.setSelectionForeground(newValue);
 }
 public Color getSelectionForeground() {
   return sourceList.getSelectionForeground();
 }
 private void clearSourceSelected() {
   Object selected[] = sourceList.getSelectedValues();
   for (int i = selected.length - 1; i >= 0; --i) {
     sourceListModel.removeElement(selected[i]);
   }
   sourceList.getSelectionModel().clearSelection();
 }
 private void clearDestinationSelected() {
   Object selected[] = destList.getSelectedValues();
   for (int i = selected.length - 1; i >= 0; --i) {
     destListModel.removeElement(selected[i]);
   }
   destList.getSelectionModel().clearSelection();
 }
 private void initScreen() {
   setBorder(BorderFactory.createEtchedBorder());
   setLayout(new GridBagLayout());
   sourceLabel = new JLabel(DEFAULT_SOURCE_CHOICE_LABEL);
   sourceListModel = new SortedListModel();
   sourceList = new JList(sourceListModel);
   add(sourceLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0,
       GridBagConstraints.CENTER, GridBagConstraints.NONE,
       EMPTY_INSETS, 0, 0));
   add(new JScrollPane(sourceList), new GridBagConstraints(0, 1, 1, 5, .5,
       1, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
       EMPTY_INSETS, 0, 0));
   addButton = new JButton(ADD_BUTTON_LABEL);
   add(addButton, new GridBagConstraints(1, 2, 1, 2, 0, .25,
       GridBagConstraints.CENTER, GridBagConstraints.NONE,
       EMPTY_INSETS, 0, 0));
   addButton.addActionListener(new AddListener());
   removeButton = new JButton(REMOVE_BUTTON_LABEL);
   add(removeButton, new GridBagConstraints(1, 4, 1, 2, 0, .25,
       GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(
           0, 5, 0, 5), 0, 0));
   removeButton.addActionListener(new RemoveListener());
   destLabel = new JLabel(DEFAULT_DEST_CHOICE_LABEL);
   destListModel = new SortedListModel();
   destList = new JList(destListModel);
   add(destLabel, new GridBagConstraints(2, 0, 1, 1, 0, 0,
       GridBagConstraints.CENTER, GridBagConstraints.NONE,
       EMPTY_INSETS, 0, 0));
   add(new JScrollPane(destList), new GridBagConstraints(2, 1, 1, 5, .5,
       1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
       EMPTY_INSETS, 0, 0));
 }
 public static void main(String args[]) {
   JFrame f = new JFrame("Dual List Box Tester");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   DualListBox dual = new DualListBox();
   dual.addSourceElements(new String[] { "One", "Two", "Three" });
   dual.addSourceElements(new String[] { "Four", "Five", "Six" });
   dual.addSourceElements(new String[] { "Seven", "Eight", "Nine" });
   dual.addSourceElements(new String[] { "Ten", "Eleven", "Twelve" });
   dual
       .addSourceElements(new String[] { "Thirteen", "Fourteen",
           "Fifteen" });
   dual.addSourceElements(new String[] { "Sixteen", "Seventeen",
       "Eighteen" });
   dual.addSourceElements(new String[] { "Nineteen", "Twenty", "Thirty" });
   f.getContentPane().add(dual, BorderLayout.CENTER);
   f.setSize(400, 300);
   f.setVisible(true);
 }
 private class AddListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     Object selected[] = sourceList.getSelectedValues();
     addDestinationElements(selected);
     clearSourceSelected();
   }
 }
 private class RemoveListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     Object selected[] = destList.getSelectedValues();
     addSourceElements(selected);
     clearDestinationSelected();
   }
 }

} class SortedListModel extends AbstractListModel {

 SortedSet model;
 public SortedListModel() {
   model = new TreeSet();
 }
 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 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;
 }

}

      </source>
   
  
 
  



Dual Sample: JList and ComboBox

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; public class DualSample {

 public static void main(String args[]) {
   String labels[] = { "A", "B", "C", "D","E", "F", "G", "H","I", "J" };
   JFrame f = new JFrame("Sample Components");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JList list = new JList(labels);
   JScrollPane scrollPane = new JScrollPane(list);
   JComboBox comboBox = new JComboBox(labels);
   comboBox.setMaximumRowCount(4);
   Container contentPane = f.getContentPane();
   contentPane.add(comboBox, BorderLayout.NORTH);
   contentPane.add(scrollPane, BorderLayout.CENTER);
   f.setSize(300, 200);
   f.setVisible(true);
 }

}

      </source>
   
  
 
  



extends ListCellRenderer to display icons

   <source lang="java">

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.BorderLayout; import java.awt.Color; import java.awt.ruponent; import java.awt.Container; import java.awt.Font; import java.awt.Graphics; import java.awt.Polygon; import javax.swing.DefaultListCellRenderer; import javax.swing.Icon; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; public class ComplexRenderingSample {

 public static void main(String args[]) {
   Object elements[][] = {
       { new Font("Helvetica", Font.PLAIN, 20), Color.red,
           new DiamondIcon(Color.blue), "Help" },
       { new Font("TimesRoman", Font.BOLD, 14), Color.blue,
           new DiamondIcon(Color.green), "Me" },
       { new Font("Courier", Font.ITALIC, 18), Color.green,
           new DiamondIcon(Color.black), "I"m" },
       { new Font("Helvetica", Font.BOLD | Font.ITALIC, 12),
           Color.gray, new DiamondIcon(Color.magenta), "Trapped" },
       { new Font("TimesRoman", Font.PLAIN, 32), Color.pink,
           new DiamondIcon(Color.yellow), "Inside" },
       { new Font("Courier", Font.BOLD, 16), Color.yellow,
           new DiamondIcon(Color.red), "This" },
       { new Font("Helvetica", Font.ITALIC, 8), Color.darkGray,
           new DiamondIcon(Color.pink), "Computer" } };
   JFrame frame = new JFrame("Complex Renderer");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container contentPane = frame.getContentPane();
   JList jlist = new JList(elements);
   ListCellRenderer renderer = new ComplexCellRenderer();
   jlist.setCellRenderer(renderer);
   JScrollPane scrollPane = new JScrollPane(jlist);
   contentPane.add(scrollPane, BorderLayout.CENTER);
   JComboBox comboBox = new JComboBox(elements);
   comboBox.setRenderer(renderer);
   contentPane.add(comboBox, BorderLayout.NORTH);
   frame.setSize(300, 300);
   frame.setVisible(true);
 }

} class DiamondIcon implements Icon {

 private Color color;
 private boolean selected;
 private int width;
 private int height;
 private Polygon poly;
 private static final int DEFAULT_WIDTH = 10;
 private static final int DEFAULT_HEIGHT = 10;
 public DiamondIcon(Color color) {
   this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
 }
 public DiamondIcon(Color color, boolean selected) {
   this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
 }
 public DiamondIcon(Color color, boolean selected, int width, int height) {
   this.color = color;
   this.selected = selected;
   this.width = width;
   this.height = height;
   initPolygon();
 }
 private void initPolygon() {
   poly = new Polygon();
   int halfWidth = width / 2;
   int halfHeight = height / 2;
   poly.addPoint(0, halfHeight);
   poly.addPoint(halfWidth, 0);
   poly.addPoint(width, halfHeight);
   poly.addPoint(halfWidth, height);
 }
 public int getIconHeight() {
   return height;
 }
 public int getIconWidth() {
   return width;
 }
 public void paintIcon(Component c, Graphics g, int x, int y) {
   g.setColor(color);
   g.translate(x, y);
   if (selected) {
     g.fillPolygon(poly);
   } else {
     g.drawPolygon(poly);
   }
   g.translate(-x, -y);
 }

} 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;
   Icon theIcon = 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];
     theIcon = (Icon) values[2];
     theText = (String) values[3];
   } else {
     theFont = list.getFont();
     theForeground = list.getForeground();
     theText = "";
   }
   if (!isSelected) {
     renderer.setForeground(theForeground);
   }
   if (theIcon != null) {
     renderer.setIcon(theIcon);
   }
   renderer.setText(theText);
   renderer.setFont(theFont);
   return renderer;
 }

}

      </source>
   
  
 
  



Get index of first visible item

   <source lang="java">

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

}

</source>
   
  
 
  



Get index of last visible item

   <source lang="java">

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

}

</source>
   
  
 
  



Get the index of the last selected item

   <source lang="java">

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

}

</source>
   
  
 
  



Getting the Items in a JList Component

   <source lang="java">

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 items in the list
   int size = list.getModel().getSize(); // 4
   // Get all item objects
   for (int i = 0; i < size; i++) {
     Object item = list.getModel().getElementAt(i);
   }
 }

}

</source>
   
  
 
  



Getting the Selected Items in a JList Component

   <source lang="java">

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 the index of all the selected items
   int[] selectedIx = list.getSelectedIndices();
   // Get all the selected items using the indices
   for (int i = 0; i < selectedIx.length; i++) {
     Object sel = list.getModel().getElementAt(selectedIx[i]);
   }
   // Get the index of the first selected item
   int firstSelIx = list.getSelectedIndex();
 }

}

</source>
   
  
 
  



How to create list cell renderer

   <source lang="java">

import java.awt.ruponent; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class FontCellRenderer implements ListCellRenderer {

 public Component getListCellRendererComponent(final JList list,
     final Object value, final int index, final boolean isSelected,
     final boolean cellHasFocus) {
   return new JPanel() {
     public void paintComponent(Graphics g) {
       super.paintComponent(g);
       Font font = (Font) value;
       String text = font.getFamily();
       FontMetrics fm = g.getFontMetrics(font);
       g.setColor(isSelected ? list.getSelectionBackground() : list
           .getBackground());
       g.fillRect(0, 0, getWidth(), getHeight());
       g.setColor(isSelected ? list.getSelectionForeground() : list
           .getForeground());
       g.setFont(font);
       g.drawString(text, 0, fm.getAscent());
     }
     public Dimension getPreferredSize() {
       Font font = (Font) value;
       String text = font.getFamily();
       Graphics g = getGraphics();
       FontMetrics fm = g.getFontMetrics(font);
       return new Dimension(fm.stringWidth(text), fm.getHeight());
     }
   };
 }
 public static void main(String[] args) {
   JFrame frame = new ListRenderingFrame();
   frame.show();
 }

} class ListRenderingFrame extends JFrame implements ListSelectionListener {

 JLabel label = new JLabel("The quick brown fox jumps over the lazy dog");
 public ListRenderingFrame() {
   setTitle("ListRendering");
   setSize(400, 300);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   Vector fonts = new Vector();
   fonts.add(new Font("Serif", Font.PLAIN, 8));
   fonts.add(new Font("SansSerif", Font.BOLD, 12));
   fonts.add(new Font("Monospaced", Font.PLAIN, 16));
   fonts.add(new Font("Dialog", Font.ITALIC, 12));
   fonts.add(new Font("DialogInput", Font.PLAIN, 12));
   JList fontList = new JList(fonts);
   fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   fontList.setCellRenderer(new FontCellRenderer());
   JScrollPane scrollPane = new JScrollPane(fontList);
   JPanel p = new JPanel();
   p.add(scrollPane);
   fontList.addListSelectionListener(this);
   getContentPane().add(p, "Center");
   getContentPane().add(label, "South");
 }
 public void valueChanged(ListSelectionEvent evt) {
   JList source = (JList) evt.getSource();
   Font font = (Font) source.getSelectedValue();
   label.setFont(font);
 }

}

      </source>
   
  
 
  



How to use the list component

   <source lang="java">

import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListTest extends JFrame implements ListSelectionListener {

 JLabel label = new JLabel("The fox jumps over the lazy dog.");
 public ListTest() {
   setTitle("ListTest: Press control to multi-select");
   setSize(400, 300);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   String[] words = { "quick", "brown", "hungry", "wild", "silent", "huge" };
   JList wordList = new JList(words);
   JScrollPane scrollPane = new JScrollPane(wordList);
   JPanel p = new JPanel();
   p.add(scrollPane);
   wordList.addListSelectionListener(this);
   getContentPane().add(p, "South");
   getContentPane().add(label, "Center");
 }
 public void valueChanged(ListSelectionEvent evt) {
   JList source = (JList) evt.getSource();
   Object[] values = source.getSelectedValues();
   String text = "";
   for (int i = 0; i < values.length; i++) {
     String word = (String) values[i];
     text += word + " ";
   }
   label.setText("The " + text + "fox jumps over the lazy dog.");
 }
 public static void main(String[] args) {
   JFrame frame = new ListTest();
   frame.show();
 }

}

      </source>
   
  
 
  



import javax.swing.JList;

   <source lang="java">

public class Main {

 public static void main(String[] argv) throws Exception {
   String[] items = { "A", "B", "C", "D" };
   JList list = new JList(items);
   // Select the first 3 items
   int start = 0;
   int end = 2;
   list.setSelectionInterval(start, end);
 }

}

</source>
   
  
 
  



Insert an item at the beginning

   <source lang="java">

import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {

 public static void main(String[] argv) throws Exception {
   DefaultListModel model = new DefaultListModel();
   JList list = new JList(model);
   int pos = 0;
   model.add(pos, "a");
 }

}

</source>
   
  
 
  



It is also possible to set the item dimensions using a sample value:

   <source lang="java">

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

}

</source>
   
  
 
  



JList is a component that displays a list of objects: It allows the user to select one or more items.

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Font; import java.awt.GraphicsEnvironment; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class List {

 public static void main(String[] args) {
   GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
   String[] fonts = ge.getAvailableFontFamilyNames();
   final JLabel label = new JLabel("Text");
   JFrame f = new JFrame();
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPanel panel = new JPanel();
   final JList list= new JList(fonts);
   list.addListSelectionListener(new ListSelectionListener() {
     public void valueChanged(ListSelectionEvent e) {
       if (!e.getValueIsAdjusting()) {
         String name = (String) list.getSelectedValue();
         Font font = new Font(name, Font.PLAIN, 12);
         label.setFont(font);
       }
     }
   });
   panel.add(new JScrollPane(list));
   f.add(label, BorderLayout.SOUTH);
   f.add(panel);
   f.pack();
   f.setLocationRelativeTo(null);
   f.setVisible(true);
 }

}

</source>
   
  
 
  



JList: ListModel and ListSelectionModel. The ListModel handles data. ListSelectionModel works with the GUI.

   <source lang="java">

import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; public class List {

 public static void main(String[] args) {
   final DefaultListModel model = new DefaultListModel();
   final JList list = new JList(model);
   JFrame f = new JFrame();
   f.setTitle("JList models");
   
   model.addElement("A");
   model.addElement("B");
   model.addElement("C");
   model.addElement("D");
   model.addElement("E");
   JPanel panel = new JPanel();
   panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
   JPanel leftPanel = new JPanel();
   JPanel rightPanel = new JPanel();
   leftPanel.setLayout(new BorderLayout());
   rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
   list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
   list.addMouseListener(new MouseAdapter() {
     public void mouseClicked(MouseEvent e) {
       if (e.getClickCount() == 2) {
         int index = list.locationToIndex(e.getPoint());
         Object item = model.getElementAt(index);
         String text = JOptionPane.showInputDialog("Rename item", item);
         String newitem = "";
         if (text != null)
           newitem = text.trim();
         else
           return;
         if (!newitem.isEmpty()) {
           model.remove(index);
           model.add(index, newitem);
           ListSelectionModel selmodel = list.getSelectionModel();
           selmodel.setLeadSelectionIndex(index);
         }
       }
     }
   });
   leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
   leftPanel.add(new JScrollPane(list));
   JButton removeall = new JButton("Remove All");
   JButton add = new JButton("Add");
   JButton rename = new JButton("Rename");
   JButton delete = new JButton("Delete");
   add.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       String text = JOptionPane.showInputDialog("Add a new item");
       String item = null;
       if (text != null)
         item = text.trim();
       else
         return;
       if (!item.isEmpty())
         model.addElement(item);
     }
   });
   delete.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       ListSelectionModel selmodel = list.getSelectionModel();
       int index = selmodel.getMinSelectionIndex();
       if (index >= 0)
         model.remove(index);
     }
   });
   rename.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       ListSelectionModel selmodel = list.getSelectionModel();
       int index = selmodel.getMinSelectionIndex();
       if (index == -1)
         return;
       Object item = model.getElementAt(index);
       String text = JOptionPane.showInputDialog("Rename item", item);
       String newitem = null;
       if (text != null) {
         newitem = text.trim();
       } else
         return;
       if (!newitem.isEmpty()) {
         model.remove(index);
         model.add(index, newitem);
       }
     }
   });
   removeall.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       model.clear();
     }
   });
   rightPanel.add(add);
   rightPanel.add(rename);
   rightPanel.add(delete);
   rightPanel.add(removeall);
   rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));
   panel.add(leftPanel);
   panel.add(rightPanel);
   f.add(panel);
   f.setSize(350, 250);
   f.setLocationRelativeTo(null);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}

</source>
   
  
 
  



JList selection changed listener

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; 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; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class SelectingJListSample {

 public static void main(String args[]) {
   String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
   JFrame frame = new JFrame("Selecting JList");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container contentPane = frame.getContentPane();
   JList jlist = new JList(labels);
   JScrollPane scrollPane1 = new JScrollPane(jlist);
   contentPane.add(scrollPane1, BorderLayout.WEST);
   ListSelectionListener listSelectionListener = new ListSelectionListener() {
     public void valueChanged(ListSelectionEvent listSelectionEvent) {
       System.out.print("First index: " + listSelectionEvent.getFirstIndex());
       System.out.print(", 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 selectionValues[] = list.getSelectedValues();
         for (int i = 0, n = selections.length; i < n; i++) {
           if (i == 0) {
             System.out.print("  Selections: ");
           }
           System.out.print(selections[i] + "/" + selectionValues[i] + " ");
         }
         System.out.println();
       }
     }
   };
   jlist.addListSelectionListener(listSelectionListener);
   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);
 }

}


      </source>
   
  
 
  



JTextPane component is an advanced component for working with text.

   <source lang="java">

import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextPane; public class TextPane {

 public static void main(String[] args) throws Exception {
   JFrame f = new JFrame();
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   
   JTextPane textpane = new JTextPane();
   textpane.setContentType("text/html");
   textpane.setEditable(false);
   String cd = System.getProperty("user.dir") + "/";
   textpane.setPage("File:///" + cd + "test.html");
   textpane.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
   f.add(new JScrollPane(textpane));
   f.setSize(new Dimension(380, 320));
   f.setLocationRelativeTo(null);
   f.setVisible(true);
 }

}

</source>
   
  
 
  



List Data Event Demo

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 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:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution 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, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* ListDataEventDemo.java is a 1.4 example that requires the Java Look and Feel
* Graphics Repository (jlfgr-1_0.jar). You can download this file from
* http://developer.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]
* 
* I needed to put quotation marks around the path, since I use a UNIX-emulating
* shell on Win32:
* 
* java -cp ".;jars/jlfgr-1_0.jar" ListDataEventDemo [UNIX shell on Win32]
*/

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 ListDataEventDemo 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 ListDataEventDemo() {
   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 = ListDataEventDemo.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() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //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 ListDataEventDemo();
   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();
     }
   });
 }

}

      </source>
   
  
 
  



Listening for Changes to the Items in a JList Component

   <source lang="java">

import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; public class Main {

 public static void main(String[] argv) throws Exception {
   JList list = new JList();
   // Register a list data listener
   DefaultListModel model = (DefaultListModel) list.getModel();
   model.addListDataListener(new MyListDataListener());
 }

} class MyListDataListener implements ListDataListener {

 public void intervalAdded(ListDataEvent evt) {
   DefaultListModel model = (DefaultListModel) evt.getSource();
   int start = evt.getIndex0();
   int end = evt.getIndex1();
   int count = end - start + 1;
   for (int i = start; i <= end; i++) {
     Object item = model.getElementAt(i);
   }
 }
 public void intervalRemoved(ListDataEvent evt) {
   int start = evt.getIndex0();
   int end = evt.getIndex1();
   int count = end - start + 1;
 }
 public void contentsChanged(ListDataEvent evt) {
   DefaultListModel model = (DefaultListModel) evt.getSource();
   int start = evt.getIndex0();
   int end = evt.getIndex1();
   int count = end - start + 1;
   for (int i = start; i <= end; i++) {
     Object item = model.getElementAt(i);
   }
 }

}

</source>
   
  
 
  



Listening for Changes to the Selection in a JList Component

   <source lang="java">

import javax.swing.JList; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class Main {

 public static void main(String[] argv) throws Exception {
   String[] items = { "A", "B", "C", "D" };
   JList list = new JList(items);
   list.addListSelectionListener(new MyListSelectionListener());
 }

} class MyListSelectionListener implements ListSelectionListener {

 public void valueChanged(ListSelectionEvent evt) {
   if (!evt.getValueIsAdjusting()) {
     JList list = (JList) evt.getSource();
     Object[] selected = list.getSelectedValues();
     for (int i = 0; i < selected.length; i++) {
       Object sel = selected[i];
     }
   }
 }

}

</source>
   
  
 
  



ListModel Demo

   <source lang="java">

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

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 PropertiesList extends JList {

 SortedListModel model;
 Properties tipProps;
 public PropertiesList(Properties props) {
   model = new SortedListModel();
   setModel(model);
   ToolTipManager.sharedInstance().registerComponent(this);
   tipProps = props;
   addProperties(props);
 }
 private void addProperties(Properties props) {
   // Load
   Enumeration e = props.propertyNames();
   while (e.hasMoreElements()) {
     model.add(e.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();
   PropertiesList list = new PropertiesList(props);
   JScrollPane scrollPane = new JScrollPane(list);
   frame.getContentPane().add(scrollPane);
   frame.setSize(300, 300);
   frame.setVisible(true);
 }

} class SortedListModel extends AbstractListModel {

 SortedSet model;
 public SortedListModel() {
   model = new TreeSet();
 }
 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 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;
 }

}

      </source>
   
  
 
  



List selection event

   <source lang="java">

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class SelectionHandler implements ActionListener, ListSelectionListener {

 private JLabel direction;
 private JList source, destination;
 public SelectionHandler(JLabel d, JList left, JList right) {
   direction = d;
   source = left;
   destination = right;
 }
 public void actionPerformed(ActionEvent a) {
   JComboBox cb = (JComboBox) a.getSource();
   String selected = (String) cb.getSelectedItem();
   String current = direction.getText();
   if (!selected.equals(current)) {
     direction.setText(selected);
     JList temp = source;
     source = destination;
     destination = temp;
     source.clearSelection();
     destination.clearSelection();
   }
 }
 public void valueChanged(ListSelectionEvent e) {
   JList list = (JList) e.getSource();
   String item = (String) source.getSelectedValue();
   System.out.println(item);
   if (item != null && !item.equals("")) {
     removeFromSource(item);
     addToDestination(item);
   }
 }
 private void removeFromSource(String item) {
   ListModel model = source.getModel();
   Vector listData = new Vector();
   for (int i = 0; i < model.getSize(); i++) {
     listData.addElement(model.getElementAt(i));
   }
   listData.removeElement(item);
   source.setListData(listData);
 }
 private void addToDestination(String item) {
   ListModel model = destination.getModel();
   Vector listData = new Vector();
   for (int i = 0; i < model.getSize(); i++) {
     listData.addElement(model.getElementAt(i));
   }
   listData.addElement(item);
   destination.setListData(listData);
 }

}

</source>
   
  
 
  



List: Shared Data Sample

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; 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 SharedDataSample {

 public static void main(String args[]) {
       final String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
   final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);
   JFrame frame = new JFrame("Shared Data");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container contentPane = frame.getContentPane();
   JPanel panel = new JPanel();
   JComboBox comboBox1 = new JComboBox(model);
   comboBox1.setMaximumRowCount(5);
   comboBox1.setEditable(true);
   JComboBox comboBox2 = new JComboBox(model);
   comboBox2.setMaximumRowCount(5);
   comboBox2.setEditable(true);
   panel.add(comboBox1);
   panel.add(comboBox2);
   contentPane.add(panel, BorderLayout.NORTH);
   JList jlist = new JList(model);
   JScrollPane scrollPane = new JScrollPane(jlist);
   contentPane.add(scrollPane, BorderLayout.CENTER);
   JButton button = new JButton("Add");
   contentPane.add(button, BorderLayout.SOUTH);
   ActionListener actionListener = new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       int index = (int) (Math.random() * labels.length);
       model.addElement(labels[index]);
     }
   };
   button.addActionListener(actionListener);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}


      </source>
   
  
 
  



List with and without ScrollPane

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; public class TenJList {

 public static void main(String args[]) {
       String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
   JFrame f = new JFrame("Example JList");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JList jlistNoScroll = new JList(labels);
   JList jlistScroll = new JList(labels);
   Container c = f.getContentPane();
   c.add(jlistNoScroll, BorderLayout.WEST);
   JScrollPane sp = new JScrollPane(jlistScroll);
   c.add(sp, BorderLayout.EAST);
   f.setSize(300, 200);
   f.setVisible(true);
 }

}

      </source>
   
  
 
  



List with textfield input

   <source lang="java">

import java.awt.Dimension; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.ResultSet; import java.sql.SQLException; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRole; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListModel; import javax.swing.border.EmptyBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListInput extends JPanel implements ListSelectionListener,

   ActionListener {
 protected JLabel label;
 protected JTextField textfield;
 protected JList list;
 protected JScrollPane scrollPane;
 public ListInput(String[] data, String title) {
   setLayout(null);
   setBorder(new EmptyBorder(5, 5, 5, 5));
   label = new ListInputLabel(title, JLabel.LEFT);
   add(label);
   textfield = new ListInputText();
   textfield.addActionListener(this);
   label.setLabelFor(textfield); // NEW
   add(textfield);
   list = new ListInputList(data);
   list.setVisibleRowCount(4);
   list.addListSelectionListener(this);
   scrollPane = new JScrollPane(list);
   add(scrollPane);
 }
 public ListInput(String title, int numCols) {
   setLayout(null);
   setBorder(new EmptyBorder(5, 5, 5, 5));
   label = new ListInputLabel(title, JLabel.LEFT);
   add(label);
   textfield = new ListInputText(numCols);
   textfield.addActionListener(this);
   label.setLabelFor(textfield); // NEW
   add(textfield);
   list = new ListInputList();
   list.setVisibleRowCount(4);
   list.addListSelectionListener(this);
   scrollPane = new JScrollPane(list);
   add(scrollPane);
 }
 public void setToolTipText(String text) {
   super.setToolTipText(text);
   label.setToolTipText(text);
   textfield.setToolTipText(text);
   list.setToolTipText(text);
 }
 public void setDisplayedMnemonic(char ch) {
   label.setDisplayedMnemonic(ch);
 }
 public void setSelected(String sel) {
   list.setSelectedValue(sel, true);
   textfield.setText(sel);
 }
 public String getSelected() {
   return textfield.getText();
 }
 public void setSelectedInt(int value) {
   setSelected(Integer.toString(value));
 }
 public int getSelectedInt() {
   try {
     return Integer.parseInt(getSelected());
   } catch (NumberFormatException ex) {
     return -1;
   }
 }
 public void valueChanged(ListSelectionEvent e) {
   Object obj = list.getSelectedValue();
   if (obj != null)
     textfield.setText(obj.toString());
 }
 public void actionPerformed(ActionEvent e) {
   ListModel model = list.getModel();
   String key = textfield.getText().toLowerCase();
   for (int i = 0; i < model.getSize(); i++) {
     String data = (String) model.getElementAt(i);
     if (data.toLowerCase().startsWith(key)) {
       list.setSelectedValue(data, true);
       break;
     }
   }
 }
 public void addListSelectionListener(ListSelectionListener lst) {
   list.addListSelectionListener(lst);
 }
 public Dimension getPreferredSize() {
   Insets ins = getInsets();
   Dimension labelSize = label.getPreferredSize();
   Dimension textfieldSize = textfield.getPreferredSize();
   Dimension scrollPaneSize = scroll.getPreferredSize();
   int w = Math.max(Math.max(labelSize.width, textfieldSize.width),
       scrollPaneSize.width);
   int h = labelSize.height + textfieldSize.height + scrollPaneSize.height;
   return new Dimension(w + ins.left + ins.right, h + ins.top + ins.bottom);
 }
 public Dimension getMaximumSize() {
   return getPreferredSize();
 }
 public Dimension getMinimumSize() {
   return getPreferredSize();
 }
 public void doLayout() {
   Insets ins = getInsets();
   Dimension size = getSize();
   int x = ins.left;
   int y = ins.top;
   int w = size.width - ins.left - ins.right;
   int h = size.height - ins.top - ins.bottom;
   Dimension labelSize = label.getPreferredSize();
   label.setBounds(x, y, w, labelSize.height);
   y += labelSize.height;
   Dimension textfieldSize = textfield.getPreferredSize();
   textfield.setBounds(x, y, w, textfieldSize.height);
   y += textfieldSize.height;
   scrollPane.setBounds(x, y, w, h - y);
 }
 public void appendResultSet(ResultSet results, int index,
     boolean toTitleCase) {
   textfield.setText("");
   DefaultListModel model = new DefaultListModel();
   try {
     while (results.next()) {
       String str = results.getString(index);
       if (toTitleCase) {
         str = Character.toUpperCase(str.charAt(0))
             + str.substring(1);
       }
       model.addElement(str);
     }
   } catch (SQLException ex) {
     System.err.println("appendResultSet: " + ex.toString());
   }
   list.setModel(model);
   if (model.getSize() > 0)
     list.setSelectedIndex(0);
 }
 class ListInputLabel extends JLabel {
   public ListInputLabel(String text, int alignment) {
     super(text, alignment);
   }
   public AccessibleContext getAccessibleContext() {
     return ListInput.this.getAccessibleContext();
   }
 }
 class ListInputText extends JTextField {
   public ListInputText() {
   }
   public ListInputText(int numCols) {
     super(numCols);
   }
   public AccessibleContext getAccessibleContext() {
     return ListInput.this.getAccessibleContext();
   }
 }
 class ListInputList extends JList {
   public ListInputList() {
   }
   public ListInputList(String[] data) {
     super(data);
   }
   public AccessibleContext getAccessibleContext() {
     return ListInput.this.getAccessibleContext();
   }
 }
 // Accessibility Support
 public AccessibleContext getAccessibleContext() {
   if (accessibleContext == null)
     accessibleContext = new AccessibleOpenList();
   return accessibleContext;
 }
 protected class AccessibleOpenList extends AccessibleJComponent {
   public String getAccessibleName() {
     System.out.println("getAccessibleName: " + accessibleName);
     if (accessibleName != null)
       return accessibleName;
     return label.getText();
   }
   public AccessibleRole getAccessibleRole() {
     return AccessibleRole.LIST;
   }
 }
 public static void main(String[] a) {
   String[] fontNames = new String[] { "Roman", "Times Roman" };
   ListInput lstFontName = new ListInput(fontNames, "Name:");
   lstFontName.setDisplayedMnemonic("n");
   lstFontName.setToolTipText("Font name");
   JFrame f = new JFrame();
   f.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   f.getContentPane().add(lstFontName);
   f.pack();
   f.setSize(new Dimension(300, 200));
   f.show();
 }

}


      </source>
   
  
 
  



Make the number of visible rows dependent on the height of the list, the visibleRowCount property must be set to 0:

   <source lang="java">

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);
   // Make the number of rows dynamic
   list.setVisibleRowCount(0);
 }

}

</source>
   
  
 
  



Methods are used to find an item:

   <source lang="java">

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

}

</source>
   
  
 
  



Methods are used to remove items

   <source lang="java">

import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {

 public static void main(String[] argv) throws Exception {
   DefaultListModel model = new DefaultListModel();
   JList list = new JList(model);
   // Remove the first item
   int pos = 0;
   model.remove(pos);
   // Remove the last item
   pos = model.getSize() - 1;
   if (pos >= 0) {
     model.remove(pos);
   }
   // Remove all items
   model.clear();
 }

}

</source>
   
  
 
  



Model for a JButton: manage only the state of the button

   <source lang="java">

import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultButtonModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class ButtonModel {

 public static void main(String[] args) {
   final JButton ok = new JButton("ok");
   JCheckBox cb = new JCheckBox("Enabled", true);
   ok.setBounds(40, 30, 80, 25);
   ok.addChangeListener(new ChangeListener() {
     public void stateChanged(ChangeEvent e) {
       DefaultButtonModel model = (DefaultButtonModel) ok.getModel();
       if (model.isEnabled())
         System.out.println("Enabled: true");
       else
         System.out.println("Enabled: false");
       if (model.isArmed())
         System.out.println("Armed: true");
       else
         System.out.println("Armed: false");
       if (model.isPressed())
         System.out.println("Pressed: true");
       else
         System.out.println("Pressed: false");
     }
   });
   cb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (ok.isEnabled())
         ok.setEnabled(false);
       else
         ok.setEnabled(true);
     }
   });
   JFrame f = new JFrame();
   f.setLayout(new FlowLayout());
   f.add(ok);
   f.add(cb);
   f.setSize(350, 250);
   f.setLocationRelativeTo(null);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}

</source>
   
  
 
  



ModifyModelSample: ListModel Demo

   <source lang="java">

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Enumeration; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; public class ModifyModelSample {

 static String labels[] = { "Chardonnay", "Sauvignon", "Riesling",
     "Cabernet", "Zinfandel", "Merlot", "Pinot Noir", "Sauvignon Blanc",
     "Syrah", "Gewurztraminer" };
 public static void main(String args[]) {
   JFrame frame = new JFrame("Modifying Model");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container contentPane = frame.getContentPane();
   // 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);
   contentPane.add(scrollPane1, BorderLayout.WEST);
   final JTextArea textArea = new JTextArea();
   textArea.setEditable(false);
   JScrollPane scrollPane2 = new JScrollPane(textArea);
   contentPane.add(scrollPane2, 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) {
       StringWriter sw = new StringWriter();
       PrintWriter pw = new PrintWriter(sw);
       switch (listDataEvent.getType()) {
       case ListDataEvent.CONTENTS_CHANGED:
         pw.print("Type: Contents Changed");
         break;
       case ListDataEvent.INTERVAL_ADDED:
         pw.print("Type: Interval Added");
         break;
       case ListDataEvent.INTERVAL_REMOVED:
         pw.print("Type: Interval Removed");
         break;
       }
       pw.print(", Index0: " + listDataEvent.getIndex0());
       pw.print(", Index1: " + listDataEvent.getIndex1());
       DefaultListModel theModel = (DefaultListModel) listDataEvent
           .getSource();
       Enumeration elements = theModel.elements();
       pw.print(", Elements: ");
       while (elements.hasMoreElements()) {
         pw.print(elements.nextElement());
         pw.print(",");
       }
       pw.println();
       textArea.append(sw.toString());
     }
   };
   model.addListDataListener(listDataListener);
   // Setup buttons
   JPanel jp = new JPanel(new GridLayout(2, 1));
   JPanel jp1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
   JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
   jp.add(jp1);
   jp.add(jp2);
   JButton jb = new JButton("add F");
   jp1.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       model.add(0, "First");
     }
   });
   jb = new JButton("addElement L");
   jp1.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       model.addElement("Last");
     }
   });
   jb = new JButton("insertElementAt M");
   jp1.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       int size = model.getSize();
       model.insertElementAt("Middle", size / 2);
     }
   });
   jb = new JButton("set F");
   jp1.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       int size = model.getSize();
       if (size != 0)
         model.set(0, "New First");
     }
   });
   jb = new JButton("setElementAt L");
   jp1.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       int size = model.getSize();
       if (size != 0)
         model.setElementAt("New Last", size - 1);
     }
   });
   jb = new JButton("load 10");
   jp1.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       for (int i = 0, n = labels.length; i < n; i++) {
         model.addElement(labels[i]);
       }
     }
   });
   jb = new JButton("clear");
   jp2.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       model.clear();
     }
   });
   jb = new JButton("remove F");
   jp2.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       int size = model.getSize();
       if (size != 0)
         model.remove(0);
     }
   });
   jb = new JButton("removeAllElements");
   jp2.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       model.removeAllElements();
     }
   });
   jb = new JButton("removeElement "Last"");
   jp2.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       model.removeElement("Last");
     }
   });
   jb = new JButton("removeElementAt M");
   jp2.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       int size = model.getSize();
       if (size != 0)
         model.removeElementAt(size / 2);
     }
   });
   jb = new JButton("removeRange FM");
   jp2.add(jb);
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       int size = model.getSize();
       if (size != 0)
         model.removeRange(0, size / 2);
     }
   });
   contentPane.add(jp, BorderLayout.SOUTH);
   frame.setSize(640, 300);
   frame.setVisible(true);
 }

}

      </source>
   
  
 
  



Multiple ranges of selected items are allowed

   <source lang="java">

import javax.swing.DefaultListSelectionModel; 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.setSelectionMode(DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
 }

}

</source>
   
  
 
  



React to list selection action

   <source lang="java">

import java.awt.Container; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class FontDialog extends JFrame implements ActionListener,

   ListSelectionListener {
 private JList style = new JList(new String[] { "Serif", "SansSerif",
     "Monospaced", "Dialog", "DialogInput" });
 private JCheckBox bold = new JCheckBox("Bold");
 private JCheckBox italic = new JCheckBox("Italic");
 private JTextField size = new JTextField("10", 2);
 private JTextField sample = new JTextField();
 public FontDialog() {
   setTitle("FontDialog");
   setSize(600, 200);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   Container contentPane = getContentPane();
   GridBagLayout gbl = new GridBagLayout();
   contentPane.setLayout(gbl);
   style.setSelectedIndex(0);
   JLabel label = new JLabel("Size: ");
   sample.setEditable(false);
   getContentPane().add(new JScrollPane(style));
   getContentPane().add(bold);
   getContentPane().add(italic);
   getContentPane().add(label);
   getContentPane().add(size);
   getContentPane().add(sample);
   sample.setText("The quick brown fox");
   bold.addActionListener(this);
   italic.addActionListener(this);
   style.addListSelectionListener(this);
   size.addActionListener(this);
 }
 public void valueChanged(ListSelectionEvent evt) {
   updateFont();
 }
 public void actionPerformed(ActionEvent evt) {
   updateFont();
 }
 public void updateFont() {
   Font font = new Font((String) style.getSelectedValue(), (bold
       .isSelected() ? Font.BOLD : 0)
       + (italic.isSelected() ? Font.ITALIC : 0), Integer
       .parseInt(size.getText()));
   sample.setFont(font);
   repaint();
 }
 public static void main(String[] args) {
   Frame f = new FontDialog();
   f.show();
 }

}

      </source>
   
  
 
  



Return the selected item objects:

   <source lang="java">

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 the first selected item
   Object firstSel = list.getSelectedValue();
   // Get all selected items without using indices
   Object[] selected = list.getSelectedValues();
 }

}

</source>
   
  
 
  



Select all the items

   <source lang="java">

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 = list.getModel().getSize() - 1;
   if (end >= 0) {
     list.setSelectionInterval(start, end);
   }
 }

}

</source>
   
  
 
  



Select a single item

   <source lang="java">

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

}

</source>
   
  
 
  



Select the first item

   <source lang="java">

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.setSelectionInterval(start, end);
 }

}

</source>
   
  
 
  



Set method replaces an item

   <source lang="java">

import javax.swing.DefaultListModel; import javax.swing.JList; public class Main {

 public static void main(String[] argv) throws Exception {
   DefaultListModel model = new DefaultListModel();
   JList list = new JList(model);
   // Replace the 2nd item
   int pos = 1;
   model.set(pos, "b");
 }

}

</source>
   
  
 
  



Setting a Tool Tip for an Item in a JList Component

   <source lang="java">

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

}

</source>
   
  
 
  



Setting the Dimensions of an Item in a JList Component

   <source lang="java">

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

}

</source>
   
  
 
  



Setting the Selected Items in a JList Component

   <source lang="java">

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

}

</source>
   
  
 
  



Setting the Selection Mode of a JList Component

   <source lang="java">

import javax.swing.DefaultListSelectionModel; 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 the current selection model mode
   int mode = list.getSelectionMode(); // MULTIPLE_INTERVAL_SELECTION
   // Only one item can be selected
   list.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
 }

}

</source>
   
  
 
  



Set visible row count and fixed cell height and width

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; 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);
   Container contentPane = frame.getContentPane();
   JList jlist1 = new JList(labels);
   jlist1.setVisibleRowCount(4);
   DefaultListModel model = new DefaultListModel();
   model.ensureCapacity(1000);
   for (int i = 0; i < 100; i++) {
     for (int j = 0; j < 10; j++) {
       model.addElement(labels[j]);
     }
   }
   JScrollPane scrollPane1 = new JScrollPane(jlist1);
   contentPane.add(scrollPane1, BorderLayout.NORTH);
   JList jlist2 = new JList(model);
   jlist2.setVisibleRowCount(4);
   jlist2.setFixedCellHeight(12);
   jlist2.setFixedCellWidth(200);
   JScrollPane scrollPane2 = new JScrollPane(jlist2);
   contentPane.add(scrollPane2, BorderLayout.CENTER);
   JList jlist3 = new JList(labels);
   jlist3.setVisibleRowCount(4);
   contentPane.add(jlist3, BorderLayout.SOUTH);
   frame.setSize(300, 350);
   frame.setVisible(true);
 }

}

      </source>
   
  
 
  



Sharing a Model between a JList and JComboBox

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Color; import java.awt.ruponent; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ruboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListIt {

 final String partsList[][] = { { "Item 1", "10", "99c" },
     { "Item 2", "12", "$18.99" }, { "Item 3", "1", "$10.00" } };
 class PartsListModel extends DefaultListModel implements ComboBoxModel {
   Object currentValue;
   public PartsListModel() {
     for (int i = 0, n = partsList.length; i < n; i++) {
       addElement(partsList[i]);
     }
   }
   // ComboBoxModel methods
   public Object getSelectedItem() {
     return currentValue;
   }
   public void setSelectedItem(Object anObject) {
     currentValue = anObject;
     fireContentsChanged(this, -1, -1);
   }
 }
 class MyLabelRenderer extends JLabel implements ListCellRenderer {
   public MyLabelRenderer() {
     setOpaque(true);
   }
   public Component getListCellRendererComponent(JList list, Object value,
       int index, boolean isSelected, boolean cellHasFocus) {
     if (value != null) {
       String values[] = (String[]) value;
       String setting = values[0] + " / " + values[1] + " / "
           + values[2];
       setText(setting);
     }
     setBackground(isSelected ? Color.BLUE : Color.WHITE);
     setForeground(isSelected ? Color.WHITE : Color.BLUE);
     return this;
   }
 }
 public ListIt() {
   JFrame f = new JFrame();
   final PartsListModel pcm = new PartsListModel();
   ListCellRenderer lcr = new MyLabelRenderer();
   JList jl = new JList(pcm);
   jl.setCellRenderer(lcr);
   ListSelectionModel lsm = jl.getSelectionModel();
   lsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   jl.addListSelectionListener(new ListSelectionListener() {
     public void valueChanged(ListSelectionEvent e) {
       if (!e.getValueIsAdjusting()) {
         String element[] = (String[]) pcm.getElementAt(e
             .getFirstIndex());
         System.out.println(element[0] + " : " + element[1] + " : "
             + element[2]);
       }
     }
   });
   JScrollPane jsp = new JScrollPane(jl);
   JComboBox jc = new JComboBox(pcm);
   jc.setRenderer(lcr);
   JButton jb = new JButton("Add Merchandise");
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       pcm.addElement(partsList[(int) (Math.random() * partsList.length)]);
     }
   });
   Container c = f.getContentPane();
   c.add(jsp, BorderLayout.NORTH);
   c.add(jc, BorderLayout.CENTER);
   c.add(jb, BorderLayout.SOUTH);
   f.setSize(250, 250);
   f.show();
 }
 public static void main(String args[]) {
   new ListIt();
 }

}


      </source>
   
  
 
  



Tab list renderer

   <source lang="java">

import java.awt.BorderLayout; import java.awt.ruponent; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.StringTokenizer; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; public class TabRenendererList extends JFrame {

 protected JList list;
 public TabRenendererList() {
   super("Swing List with Tab Renenderer");
   setSize(500, 240);
   String[] items = { "cloumn 1\t column  2\t Column 3",
       "cloumn 1\t column  2\t Column 3" };
   list = new JList(items);
   TabListCellRenderer renderer = new TabListCellRenderer();
   list.setCellRenderer(renderer);
   JScrollPane scrollPane = new JScrollPane();
   scrollPane.getViewport().add(list);
   getContentPane().add(scrollPane, BorderLayout.CENTER);
   WindowListener exitEvent = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   };
   addWindowListener(exitEvent);
   setVisible(true);
 }
 public static void main(String argv[]) {
   new TabRenendererList();
 }

} class TabListCellRenderer extends JLabel implements ListCellRenderer {

 protected static Border m_noFocusBorder = new EmptyBorder(1, 1, 1, 1);
 protected FontMetrics m_fm = null;
 public TabListCellRenderer() {
   super();
   setOpaque(true);
   setBorder(m_noFocusBorder);
 }
 public Component getListCellRendererComponent(JList list, Object value,
     int index, boolean isSelected, boolean cellHasFocus) {
   setText(value.toString());
   setBackground(isSelected ? list.getSelectionBackground() : list
       .getBackground());
   setForeground(isSelected ? list.getSelectionForeground() : list
       .getForeground());
   setFont(list.getFont());
   setBorder((cellHasFocus) ? UIManager
       .getBorder("List.focusCellHighlightBorder") : m_noFocusBorder);
   return this;
 }
 public void paint(Graphics g) {
   m_fm = g.getFontMetrics();
   g.setColor(getBackground());
   g.fillRect(0, 0, getWidth(), getHeight());
   getBorder().paintBorder(this, g, 0, 0, getWidth(), getHeight());
   g.setColor(getForeground());
   g.setFont(getFont());
   Insets insets = getInsets();
   int x = insets.left;
   int y = insets.top + m_fm.getAscent();
   StringTokenizer st = new StringTokenizer(getText(), "\t");
   while (st.hasMoreTokens()) {
     String str = st.nextToken();
     g.drawString(str, x, y);
     //insert distance for each tab
     x += m_fm.stringWidth(str) + 50;
     if (!st.hasMoreTokens())
       break;
   }
 }

}

      </source>
   
  
 
  



Test of the DragGesture classes and JList to see if we can recognize a simple drag gesture

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// GestureTest.java //A simple (?) test of the DragGesture classes to see if we //can recognize a simple drag gesture. // import java.awt.BorderLayout; 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.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; public class GestureTest extends JFrame implements DragGestureListener {

 DragSource ds;
 JList jl;
 String[] items = { "Java", "C", "C++", "Lisp", "Perl", "Python" };
 public GestureTest() {
   super("Gesture Test");
   setSize(200, 150);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent we) {
       System.exit(0);
     }
   });
   jl = new JList(items);
   jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   getContentPane().add(new JScrollPane(jl), BorderLayout.CENTER);
   ds = new DragSource();
   DragGestureRecognizer dgr = ds.createDefaultDragGestureRecognizer(jl,
       DnDConstants.ACTION_COPY, this);
   setVisible(true);
 }
 public void dragGestureRecognized(DragGestureEvent dge) {
   System.out.println("Drag Gesture Recognized!");
 }
 public static void main(String args[]) {
   new GestureTest();
 }

}


      </source>
   
  
 
  



The items can be arbitrary objects. The toString() method of the objects is displayed in the list component.

   <source lang="java">

import javax.swing.JList; public class Main {

 public static void main(String[] argv) throws Exception {
   Object[] items2 = { new Integer(123), new java.util.Date() };
   JList list = new JList(items2);
   
   
 }

}

</source>
   
  
 
  



The selected items must be in a contiguous range

   <source lang="java">

import javax.swing.DefaultListSelectionModel; 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.setSelectionMode(DefaultListSelectionModel.SINGLE_INTERVAL_SELECTION);
 }

}

</source>
   
  
 
  



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

   <source lang="java">

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

}

</source>
   
  
 
  



Triple List from same data array

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import javax.swing.Box; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; public class TripleListSample {

 public static void main(String args[]) {
       String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
   JFrame f = new JFrame("Selection Modes");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JList list1 = new JList(labels);
   JList list2 = new JList(labels);
   JList list3 = new JList(labels);
   Container c = f.getContentPane();
   JScrollPane sp1 = new JScrollPane(list1);
   sp1.setColumnHeaderView(new JLabel("Single Selection"));
   JScrollPane sp2 = new JScrollPane(list2);
   sp2.setColumnHeaderView(new JLabel("Single Interval"));
   JScrollPane sp3 = new JScrollPane(list3);
   sp3.setColumnHeaderView(new JLabel("Multi Interval"));
   Box box = Box.createHorizontalBox();
   box.add(sp1);
   box.add(sp2);
   box.add(sp3);
   c.add(box, BorderLayout.CENTER);
   f.setSize(300, 200);
   f.setVisible(true);
 }

}


      </source>
   
  
 
  



Use JList component to display custom objects with ListCellRenderer

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// SwingListExample.java //An example of the JList component in action. This program uses a custom //renderer (BookCellRenderer.java) to show a list of books with icons of their //covers. // import java.awt.BorderLayout; import java.awt.Color; import java.awt.ruponent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; public class SwingListExample extends JPanel {

 private BookEntry books[] = {
     new BookEntry("Ant: The Definitive Guide", "1.gif"),
     new BookEntry("Database Programming with JDBC and Java",
         "2.gif"),
     new BookEntry("Developing Java Beans", "3.gif"),
     new BookEntry("Developing JSP Custom Tag Libraries",
         "4.gif"),
     new BookEntry("Java 2D Graphics", "4.gif"),
     new BookEntry("Java and XML", "5.gif"),
     new BookEntry("Java and XSLT", "1.gif"),
     new BookEntry("Java and SOAP", "2.gif"),
     new BookEntry("Learning Java", "3.gif") };
 private JList booklist = new JList(books);
 public SwingListExample() {
   setLayout(new BorderLayout());
   JButton button = new JButton("Print");
   button.addActionListener(new PrintListener());
   booklist = new JList(books);
   booklist.setCellRenderer(new BookCellRenderer());
   booklist.setVisibleRowCount(4);
   JScrollPane pane = new JScrollPane(booklist);
   add(pane, BorderLayout.NORTH);
   add(button, BorderLayout.SOUTH);
 }
 public static void main(String s[]) {
   JFrame frame = new JFrame("List Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(new SwingListExample());
   frame.pack();
   frame.setVisible(true);
 }
 // An inner class to respond to clicks on the Print button
 class PrintListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     int selected[] = booklist.getSelectedIndices();
     System.out.println("Selected Elements:  ");
     for (int i = 0; i < selected.length; i++) {
       BookEntry element = (BookEntry) booklist.getModel()
           .getElementAt(selected[i]);
       System.out.println("  " + element.getTitle());
     }
   }
 }

} class BookEntry {

 private final String title;
 private final String imagePath;
 private ImageIcon image;
 public BookEntry(String title, String imagePath) {
   this.title = title;
   this.imagePath = imagePath;
 }
 public String getTitle() {
   return title;
 }
 public ImageIcon getImage() {
   if (image == null) {
     image = new ImageIcon(imagePath);
   }
   return image;
 }
 // Override standard toString method to give a useful result
 public String toString() {
   return title;
 }

} class BookCellRenderer extends JLabel implements ListCellRenderer {

 private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
 public BookCellRenderer() {
   setOpaque(true);
   setIconTextGap(12);
 }
 public Component getListCellRendererComponent(JList list, Object value,
     int index, boolean isSelected, boolean cellHasFocus) {
   BookEntry entry = (BookEntry) value;
   setText(entry.getTitle());
   setIcon(entry.getImage());
   if (isSelected) {
     setBackground(HIGHLIGHT_COLOR);
     setForeground(Color.white);
   } else {
     setBackground(Color.white);
     setForeground(Color.black);
   }
   return this;
 }

}

      </source>
   
  
 
  



Weak ListModel

   <source lang="java">

import java.io.Serializable; import java.util.*; import java.lang.ref.*; import javax.swing.*; import javax.swing.event.*; class WeakListModel implements ListModel, Serializable {

 private final Object present = new Object();
 private Map listenerList = Collections.synchronizedMap(new WeakHashMap());
 private ArrayList delegate = new ArrayList();
 public int getSize() {
   return delegate.size();
 }
 public Object getElementAt(int index) {
   return delegate.get(index);
 }
 public void trimToSize() {
   delegate.trimToSize();
 }
 public void ensureCapacity(int minCapacity) {
   delegate.ensureCapacity(minCapacity);
 }
 public int size() {
   return delegate.size();
 }
 public boolean isEmpty() {
   return delegate.isEmpty();
 }
 public Enumeration elements() {
   return Collections.enumeration(delegate);
 }
 public boolean contains(Object elem) {
   return delegate.contains(elem);
 }
 public int indexOf(Object elem) {
   return delegate.indexOf(elem);
 }
 public int lastIndexOf(Object elem) {
   return delegate.lastIndexOf(elem);
 }
 public Object elementAt(int index) {
   return delegate.get(index);
 }
 public Object firstElement() {
   return delegate.get(0);
 }
 public Object lastElement() {
   return delegate.get(delegate.size()-1);
 }
 public void setElementAt(Object obj, int index) {
   delegate.set(index, obj);
   fireContentsChanged(this, index, index);
 }
 public void removeElementAt(int index) {
   delegate.remove(index);
   fireIntervalRemoved(this, index, index);
 }
 public void insertElementAt(Object obj, int index) {
   delegate.add(index, obj);
   fireIntervalAdded(this, index, index);
 }
 public void addElement(Object obj) {
   int index = delegate.size();
   delegate.add(obj);
   fireIntervalAdded(this, index, index);
 }
 public boolean removeElement(Object obj) {
   int index = indexOf(obj);
   boolean rv = delegate.remove(obj);
   if (index >= 0) {
     fireIntervalRemoved(this, index, index);
   }
   return rv;
 }
 public void removeAllElements() {
   int index1 = delegate.size()-1;
   delegate.clear();
   if (index1 >= 0) {
     fireIntervalRemoved(this, 0, index1);
   }
 }
 public String toString() {
   return delegate.toString();
 }
 public synchronized void addListDataListener(ListDataListener l) {
   listenerList.put(l, present);
 }
 public synchronized void removeListDataListener(ListDataListener l) {
   listenerList.remove(l);
 }
 protected synchronized void fireContentsChanged(Object source, int index0, int index1) {
   ListDataEvent e = null;
   Set set = new HashSet(listenerList.keySet());
   Iterator iter = set.iterator();
   while (iter.hasNext()) {
     if (e == null) {
       e = new ListDataEvent(source, ListDataEvent.CONTENTS_CHANGED, index0, index1);
     }
     ListDataListener ldl = (ListDataListener)iter.next();
     ldl.contentsChanged(e);
   }
 }
 protected synchronized void fireIntervalAdded(Object source, int index0, int index1) {
   ListDataEvent e = null;
   Set set = new HashSet(listenerList.keySet());
   Iterator iter = set.iterator();
   while (iter.hasNext()) {
     if (e == null) {
       e = new ListDataEvent(source, ListDataEvent.INTERVAL_ADDED, index0, index1);
     }
     ListDataListener ldl = (ListDataListener)iter.next();
     ldl.intervalAdded(e);
   }
 }
 protected synchronized void fireIntervalRemoved(Object source, int index0, int index1) {
   ListDataEvent e = null;
   Set set = new HashSet(listenerList.keySet());
   Iterator iter = set.iterator();
   while (iter.hasNext()) {
     if (e == null) {
       e = new ListDataEvent(source, ListDataEvent.INTERVAL_REMOVED, index0, index1);
     }
     ListDataListener ldl = (ListDataListener)iter.next();
     ldl.intervalRemoved(e);
   }
 }
 public EventListener[] getListeners(Class listenerType) { 
   Set set = listenerList.keySet();
   return (EventListener[])set.toArray(new EventListener[0]);
 }

}

public class TestListModel {

 public static void main (String args[]) {
   ListDataListener ldl = new ListDataListener() {
     public void intervalAdded(ListDataEvent e) {
       System.out.println("Added: " + e);
     }
     public void intervalRemoved(ListDataEvent e) {
       System.out.println("Removed: " + e);
     }
     public void contentsChanged(ListDataEvent e) {
       System.out.println("Changed: " + e);
     }
   };
   WeakListModel model = new WeakListModel();
   model.addListDataListener(ldl);
   model.addElement("New Jersey");
   model.addElement("Massachusetts");
   model.addElement("Maryland");
   model.removeElement("New Jersey");
   ldl = null;
   System.gc();
   model.addElement("New Jersey");
   System.out.println(model);
 }

}

      </source>