JList Multiple Selection Example Java Swing


    In the previous program, you have seen JList with single selection. Now let us go for JList Multiple Selection.

    In the following JList Multiple Selection example, user’s multiple selected items are displayed in JOptionPane using showMessageDialog() method.

    import javax.swing.*;    
    import java.awt.*;    
    import java.awt.event.*; 
    import javax.swing.event.*;                        // for ListSelectionListener
    
    public class MultiSelectionDemo extends JFrame implements ListSelectionListener
    {
      JList places;
    
      public MultiSelectionDemo()
      {
        Container c = getContentPane(); 	
        c.setLayout(new FlowLayout());
        String names[] = {"Banglore", "Hyderabad", "Ooty", "Chennai", "Mumbai", "Delhi", "Kochi", "Darjeeling"};
        places = new JList(names) ;                    // creating JList object; pass the array as parameter
        places.setVisibleRowCount(5); 
    		     
        places.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    	
        c.add(new JScrollPane(places));
    
        places.addListSelectionListener(this);
    
        setTitle("Practcing Multiple selection JList");
        setSize(300,300);
        setVisible(true);
      }
      public void valueChanged(ListSelectionEvent e)
      {
        String destinations = "";
        Object obj[ ] = places.getSelectedValues();
        for(int i = 0; i < obj.length; i++)
        {
          destinations += (String) obj[i];
        }
    
        JOptionPane.showMessageDialog( null, "You go: " + destinations,  "Learning Multiple Selections", JOptionPane.PLAIN_MESSAGE);
      }
      public static void main( String args[ ] )
      {
        new MultiSelectionDemo();
      }
    }
    

    JList Multiple Selection

    places.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    The above statement allows the list for multiple selections. By clicking an item in the list, holding shift key and clicking on another item, makes a contiguous selection of items. To deselect, hold the ctrl key and click again.

    Object obj[] = places.getSelectedValues();

    getSelectedValues() method of JList returns an array of objects of Object class(of selected items).

    destinations += (String) obj[i];

    Object element is casted to String object and concatenated.

    Following are the methods provided by JList to know the user's selection:

    1. getSelectedValues() : returns an object array of selected items. Convert them into string.
    2. getSelectedValue() : returns an object of the seleced item and convert it into string.
    3. getSelectedIndexes() : returns an int array.
    4. getSelectedIndex() : returns an int.

Leave a Comment

Your email address will not be published.