[英]JButton Array ActionListener Issue
我正在編寫程序,但遇到了問題...
我創建了1個JLabel數組和1個JButton數組。 JLabel數組包含一個字符串,即“俱樂部名稱”。 JButton數組包含一個僅顯示“ Edit”的字符串。
然后,For循環根據clubs數組的長度填充每個數組,並為每個按鈕添加一個動作偵聽器。
當用戶單擊與JLabel對應的JButton時,它將啟動一個事件。 在這種情況下,我需要找出與JButton匹配的JLabel中存儲的值。
由於事件監聽器不知道它在循環內,因此無法使用它。
如何實現我想要的目標?
請參閱下面的代碼。
JLabel clubs[] = new JLabel[99];
JButton editAClub[] = new JButton[99];
for(int i=0; i <= (allClubs.length - 1);i++)
{
clubs[i] = new JLabel("Club " + i);
editAClub[i] = new JButton("Edit");
editAClub[i].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
selectedClub = clubs[i].getText().toString();
System.out.println(selectedClub);
}
});
}
我將創建一個Buttons和JLabels的映射,並在actionListener中傳遞操作的源:
JLabel clubs[] = new JLabel[99];
JButton editAClub[] = new JButton[99];
//create a map to store the values
final HashMap<JButton,JLabel> labelMap = new HashMap<>(); //in JDK 1.7
for(int i=0; i <= (allClubs.length - 1); i++)
{
clubs[i] = new JLabel("Club " + i);
editAClub[i] = new JButton("Edit");
//add the pair to the map
labelMap.put(editAClub[i],clubs[i]);
editAClub[i].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//get the label associated with this button from the map
selectedClub = labelMap.get(e.getSource()).getText(); // the toString() is redundant
System.out.println(selectedClub);
}
});
}
這樣,按鈕和標簽通過單獨的數據結構相互關聯,而不僅僅是它們在各自數組中的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.