Reputation: 29
I have tons of labels. My problem is that I don't know how to write that if i click label2
, then set a new image on label2
but label1
doesnt change. labels are named like A1-A10. (I actually have 92 labels, so this is getting cumbersome.) Here's my code:
public void mouseClicked(MouseEvent event) {
if (event.getSource()==A1 && (x==1)) {
A1.setIcon(new ImageIcon("zoldgomb.jpg"));
x=2;
} else if(x==2) {
A1.setIcon(new ImageIcon("sargagomb.jpg"));
x=1;
}
}
ok, i solved it, thx everybody :)
if (event.getSource() instanceof JLabel) {
if (x == 1) {
((JLabel)event.getSource()).setIcon(new ImageIcon("zoldgomb.jpg"));
x = 2;
} else if (x == 2) {
((JLabel)event.getSource()).setIcon(new ImageIcon("sargagomb.jpg"));
x = 1;
}
}
Upvotes: 1
Views: 426
Reputation: 285405
b
or s
unless they are being used for trivial purposes such as the index of a for loop. Instead use names that have some meaning so that your code becomes self-commenting. getSource()
on the MouseEvent objevct passed into your method. Your parameter is named event
above.setIcon(...)
method.Upvotes: 2