修改 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