I want to add mouseListener to all labels in the array. Every label should show an other card of the layout. If I use below code, all labels show card6. What is wrong?
sorry this is correct code..
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");
}
the problem is when
mouse-event
fire value ofi
have value6
or last value offor-loop
you can create a
jlable
class
and give ainstance
variable
likelableindex
so whenmouse-event
occurs you first get the lableindex
and then show corresponding card.or
you can getname of the jlable and get index by removing
lbl
part of thejlable
name and show corresponding card.for example if jlable name islb12
then take 2 out and show card namedcard + 2
orcard2
for example consider this example