修改 JList 中的选定元素

鉴于 JList 喜欢

JList myList = new JList(items);

列表中的选定项目可以通过 JListListSelectionModel 进行修改:

ListSelectionModel sm = myList.getSelectionModel();  
sm.clearSelection();                      // clears the selection
sm.setSelectionInterval(index, index);    // Sets a selection interval
                                          // (single element, in this case)

或者,JList 还提供了一些方便的方法来直接操作所选索引:

myList.setSelectionIndex(index);            // sets one selected index
                                            // could be used to define the Default Selection

myList.setSelectedIndices(arrayOfIndexes);  // sets all indexes contained in
                                            // the array as selected