[英]using Java mouseClicked event handler to change icons
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. 我的问题是,如果我单击
label2
,然后在label2
上设置新图像,但label1
不变,我不知道该怎么写。 labels are named like A1-A10. 标签的名称类似于A1-A10。 (I actually have 92 labels, so this is getting cumbersome.) Here's my code:
(我实际上有92个标签,所以这变得很麻烦。)这是我的代码:
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;
}
}
b
or s
unless they are being used for trivial purposes such as the index of a for loop. b
或s
。 Instead use names that have some meaning so that your code becomes self-commenting. getSource()
on the MouseEvent objevct passed into your method. getSource()
来确定按下了哪个JLabel。 Your parameter is named event
above. event
。 setIcon(...)
method. setIcon(...)
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.