Selects all elements, what equal to given argument listElement on given JList. - Java Swing

Java examples for Swing:JList

Description

Selects all elements, what equal to given argument listElement on given JList.

Demo Code


//package com.java2s;

import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListSelectionModel;

public class Main {
    /**/*from  ww  w . java2 s.  co m*/
     * Selects all elements, what equal to given argument listElement on given JList.
     * @param list JList instance.
     * @param listElement elements, which must be selected.
     * @param indexesOfDuplicates in this list indexes of selected elements will be added. This argument can be null. 
     */
    public static void selectAllElementsLike(JList list,
            Object listElement, List<Integer> indexesOfDuplicates) {
        DefaultListModel model = (DefaultListModel) list.getModel();
        ListSelectionModel sm = list.getSelectionModel();
        int lastIndex = 0;
        for (Object element : model.toArray()) {
            if (element.equals(listElement)) {
                int idx = model.indexOf(element, lastIndex);
                if (idx + 1 < model.size()) {
                    lastIndex = idx + 1; //possible Ex here
                }
                sm.addSelectionInterval(idx, idx);
                if (indexesOfDuplicates != null) {
                    indexesOfDuplicates.add(idx);
                }
            }
        }
    }
}

Related Tutorials