2013-10-18 41 views

回答

3

是的,但它需要一些handcoding,它將只爲觸摸工作(因爲你將不能夠分配焦點的話)。

我們通常建議只爲這些情況使用Component/Container層次結構,而不是處理列表,但顯然這並不總是實用的。

關鍵是總是使用列表動作監聽器來觸發事件,沒有別的。所以,當你在列表中的動作處理代碼,你想知道它是否是由您的按鈕觸發...

如果你是GUI Builder中,這是相當容易:

Button b = ((GenericListCellRenderer)list.getRenderer()).extractLastClickedComponent(); 
if(b != null && b == myButton) { 
    // your event code here for the button, the selected entry is list.getSelectedItem()/Index() 
} 

手寫代碼的方法與一個主要的警告非常相似,你沒有extractLastClickedComponent方法。所以假設你在渲染器中有一個組件,只需向它添加一個動作監聽器。在動作監聽器內只設置一個標誌例如:

myButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent ev) { 
     buttonWasClicked = true; 
    } 
}); 

// within the list listener we do the exact same thing: 
if(buttonWasClicked) { 
    // for next time... 
    buttonWasClicked = false; 

    // your event code here for the button, the selected entry is list.getSelectedItem()/Index() 
} 
+0

夏嘉曦阿爾莫格 - 非常感謝,這作品! –

+0

如果它有效,你需要接受答案,最好是upvote –