JList Multiple Selection Example Java Swing

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.

    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 Reply

Your email address will not be published. Required fields are marked *