2011-02-25 32 views
0
MyJList myList = new MyJList(); 
    myList.addListSelectionListener(new ListSelectionListener() { 

    @Override 
    public void valueChanged(ListSelectionEvent e) { 

    if(!e.getValueIsAdjusting()){ 
     System.out.println("Selected!"); 
    } 
    } 
}); 

。 。 。Listen JList setSelectedIndex

class MyList extends JList{ 


    public MyList() { 
    super(); 

    this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 

    this.setSelectedIndex(0); 

    } 

}

當我點擊鼠標列表項,我看到消息«已選擇!»。

程序啓動時,不顯示此消息,但選擇了項目#0。

回答

2

setSelectedIndex在構造

那之後,添加SelectionListener

setSelectedIndex叫...有沒有監聽

+0

你說得對。謝謝。 – Alexandr 2011-02-28 06:27:02

0

這正是應該發生的事情。只有在用戶選擇該項目時才調用valueChangedsetSelectedIndex不會調用任何偵聽器。

0

看看你的訂貨代碼:

a)您創建列表並將索引設置爲0
b)添加ListSelectionListener。自從添加了監聽器以來沒有發生任何變化,因此沒有事件被觸發。

嘗試增加:

list.setSelectedIndex(1) 

添加監聽後,看是否在事件被觸發。