Here you can find the source of setSelectedItems(JList list, List selected)
Parameter | Description |
---|---|
list | _more_ |
selected | _more_ |
public static void setSelectedItems(JList list, List selected)
//package com.java2s; /*// w w w . jav a 2 s .c o m * Copyright 1997-2016 Unidata Program Center/University Corporation for * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307, * support@unidata.ucar.edu. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.util.ArrayList; import java.util.List; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.ListModel; public class Main { /** * _more_ * * @param list _more_ * @param selected _more_ */ public static void setSelectedItems(JList list, List selected) { List items = getItems(list); int cnt = 0; int[] indices = new int[items.size()]; for (int i = 0; i < selected.size(); i++) { int idx = items.indexOf(selected.get(i)); if (idx < 0) { continue; } indices[cnt++] = idx; } if (cnt > 0) { int[] realIndices = new int[cnt]; for (int i = 0; i < cnt; i++) { realIndices[i] = indices[i]; } list.setSelectedIndices(realIndices); } } /** * return the list of items held by the combo box. * * @param box The box * @return List of items */ public static List getItems(JComboBox box) { List l = new ArrayList(); for (int i = 0; i < box.getItemCount(); i++) { l.add(box.getItemAt(i)); } return l; } /** * _more_ * * @param list _more_ * * @return _more_ */ public static List getItems(JList list) { List items = new ArrayList(); ListModel model = list.getModel(); for (int i = 0; i < model.getSize(); i++) { items.add(model.getElementAt(i)); } return items; } }