Reputation: 117
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");
}
Upvotes: 1
Views: 625
Reputation: 9862
the problem is when mouse-event
fire value of i
have value 6
or last value of for-loop
for (i = 0; i < 6; i++){}
you can create a jlable
class
and give a instance
variable
like lableindex
so when mouse-event
occurs you first get the lable index
and then show corresponding card.
or
you can getname of the jlable and get index by removing lbl
part of the jlable
name and show corresponding card.for example if jlable name is lb12
then take 2 out and show card named card + 2
or card2
for example consider this example
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);
}
Upvotes: 2