我想将mouseListener添加到数组中的所有标签中。每个标签都应该显示布局的另一张卡片。如果我使用以下代码,所有标签都显示卡片6。怎么了?
对不起,这是正确的代码。。
panList = new JPanel();
panList.setBounds(0, 0, 206, 517);
panList.setLayout(null);
cs.add(panList);
CreateCards();
int y = 0;
for(i = 0 ; i < 6; i++) {
String lblName = getString("lbl"+String.valueOf(i));
lblSettingTitle[i] = new JLabel(" "+lblName);
lblSettingTitle[i].setBounds(0, y+10, 206, 26);
lblSettingTitle[i].addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
CardLayout cardLayout = (CardLayout) cards.getLayout();
cardLayout.show(cards, "card"+String.valueOf(i));
}
});
panList.add(lblSettingTitle[i]);
y+=26;
}
}
private void CreateCards() {
card1 = new JPanel();
card2 = new JPanel();
cards = new JPanel(new CardLayout());
cards.setBounds(206, 35, 814-206, 546-120);
cs.add(cards);
cards.add(card1, "card1");
cards.add(card2, "card2");
}
问题是当i
的mouse-event
激发值为6
或for-loop
的最后一个值时
for (i = 0; i < 6; i++){}
您可以创建一个jlable
class
,并像lableindex
一样给出一个instance
variable
所以当mouse-event
发生时,您首先获得标签index
,然后显示相应的卡。
或
您可以通过删除jlable
名称的lbl
部分并显示相应的卡片来获取jable的名称和索引。例如,如果jable名称是lb12
,则取出2并显示名为card + 2
或card2
的卡片
例如,考虑这个例子
public void mouseClicked(java.awt.event.MouseEvent e) {
String index = ((JLabel)e.getSource()).getText().substring(xx,yy); // here xx , yy depend on how you are naming jlables .this should return 2 if your lable is lbl2
CardLayout cardLayout = (CardLayout) cards.getLayout();
cardLayout.show(cards, "card" + index);
System.out.println("card" + index);
}