JList Single Selection Example Java Swing


A list displays a series of items from which the user may select one or more items. Lists are created with class JList, which inherits from class JComponent. Class JList supports both single-selection lists (i.e., lists that allow only one item to be selected at a time) and multiple-selection lists (lists that allow any number of items to be selected). That is, list can be used for single selection or multiple selection. Now we discuss on JList Single Selection.
JList Single Selection

In a single-selection list, we can select only one item only. The difference with combobox is that the list displays scrollbars.

In the following JList Single Selection example, the background of the frame changes as per the color item selected by the user.

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;                       // for ListSelectionListener

public class JListDemo extends JFrame implements ListSelectionListener
{
  JList colors ;
  Container c;
	
  public JListDemo()
  {
    c = getContentPane(); 	
    c.setLayout(new FlowLayout());
    String names[] = { "Red", "Green", "Blue", "Cyan", "Magenta", "Yellow" };
                                                  // no method to add item by item separately.  All must be added through an array only

    colors = new JList(names);  	          // creating JList object
    colors.setVisibleRowCount(5); 
    colors.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	
    c.add(new JScrollPane(colors));

    colors.addListSelectionListener(this);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Practcing JList");
    setSize(300,300);
    setVisible(true);
  }
  public void valueChanged(ListSelectionEvent e)
  {
    String str = (String) colors.getSelectedValue();
    if(str.equals("Red"))
      c.setBackground(Color.red);
    else if(str.equals("Green"))
      c.setBackground(Color.green);
    else if(str.equals("Blue"))
      c.setBackground(Color.blue);
    else if(str.equals("Cyan"))
      c.setBackground(Color.cyan);
    else if(str.equals("Magenta"))
      c.setBackground(Color.magenta);
    else if(str.equals("Yellow"))
      c.setBackground(Color.yellow);
  }
  public static void main(String args[])
  {
    new JListDemo();
  }
}


JList Single Selection
Output screen of JList Single Selection Example

colors.setVisibleRowCount(5);

sets the number of visible items in the list. In other words, we are setting the size of the list to be displayed on the frame. Other items can seen using scroll bar.

colors.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

With the above statement, the list is made for single selection. Anyhow, if we do not specify, the default is single selection only. But we can make it for multiple selections also. The next program illustrates.

c.add(new JScrollPane(colors));

By default, the list does not display the scroll bar as it displays all the items. If we add the list to a JScrollPane, list with scroll bar appears.

String str = (String) colors.getSelectedValue();

getSelectedValue() returns the selected(or clicked) string item as an object of Object class and is type casted to an object of String.

ListSelectionListener is an interface defined in javax.swing.event package used with JList. It includes only one abstract method valueChanged(ListSelectionEvent e) which must be given a body in our class with the event-handling code.

Just for practice, JScrollPane is used. JList is added to JScrollPane. JScrollPane gives scroll bars, both horizontal and vertical. This does not exist in AWT.

Other modes of selection:

a) ListSelectionModel.SINGLE_SELECTION : For single selection only and is the default also.

b) ListSelectionModel.SINGLE_INTERVAL_SELECTION : allows continuous range of items selectin. Holding Shift key and clicking on the first element and the last element wanted selects all elements between two clicks.

c) ListSelectionModel. MULTIPLE_INTERVAL_SELECTION

allows single interval selection(by clicking over first and last elements) and elements here and there in the list by holding Ctrl key and clicking with mouse on the item to be selected.

A multiple-selection list enables the user to select many items from a JList. A SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items in the list by clicking the first item while holding shift key, then clicking the last item to select in the range(while holding shift key).

A MULTIPLE_INTERVAL_SELECTION list allows continuous range selection as described for a SINGLE_INTERVAL_SELECTION list and allows miscellaneous items to be selected by holding the Ctrl key while clicking each item to select. To deselect an item, hold the Ctrl key while clicking the item a second time.

Would you like to see JList with Multiple Selection.