2015-05-08 66 views
1

我只是想看看哪些元素正在被選中,並根據索引更改幀上的其他標籤和texfields。我的代碼如下:ListSelectionListener錯誤索引

list = new JList(listModel); 
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
    list.setLayoutOrientation(JList.VERTICAL); 

    list.addListSelectionListener(new ListSelectionListener() { 
     public void valueChanged(ListSelectionEvent e) { 
      System.out.println(e.getLastIndex()); 
     } 
    }); 

當我點擊第一單元輸出:0 0 單擊第二個元素後:1 1 之後,我想再次單擊第一個元素,但是這一次再次輸出爲1 1。當我嘗試了25個元素時,選擇最後一個元素,然後點擊第一個元素,輸出結果爲23 23。是關於事件的問題還是關於我的代碼?

回答

3

您得到的行爲是標準行爲,如果您想擁有不同的行爲,請創建您自己的SelectionListener,該行爲也認爲是getValueIsAdjusting()

class SharedListSelectionHandler implements ListSelectionListener { 
    public void valueChanged(ListSelectionEvent e) { 
     ListSelectionModel lsm = (ListSelectionModel)e.getSource(); 

     int firstIndex = e.getFirstIndex(); 
     int lastIndex = e.getLastIndex(); 
     boolean isAdjusting = e.getValueIsAdjusting(); 
     output.append("Event for indexes " 
         + firstIndex + " - " + lastIndex 
         + "; isAdjusting is " + isAdjusting 
         + "; selected indexes:"); 

     if (lsm.isSelectionEmpty()) { 
      output.append(" <none>"); 
     } else { 
      // Find out which indexes are selected. 
      int minIndex = lsm.getMinSelectionIndex(); 
      int maxIndex = lsm.getMaxSelectionIndex(); 
      for (int i = minIndex; i <= maxIndex; i++) { 
       if (lsm.isSelectedIndex(i)) { 
        output.append(" " + i); 
       } 
      } 
     } 
     output.append(newline); 
    } 
} 

查找here explanation of this example

+0

投訴事件源時出錯。線程「AWT-EventQueue-0」中的異常java.lang.ClassCastException:javax.swing.JList不能轉換爲javax.swing.ListSelectionModel。 ListSelectionModel lsm =(ListSelectionModel)e.getSource(); – codebender