我有一个框架,在这个框架中,我有10个标签。
如果单击标签,则应将其图标设置为“ zoldgomb.jpg”,如果单击第二次,应将其图标设置为“ sargagomb.jpg”。
这部分工作正常,现在我的问题是:如何编写该代码,这样我不必为10个标签(标签名称A1-A11)中的每一个写下十次?
if (event.getSource()==A1) {
if (x==1) {
A1.setIcon(new ImageIcon("zoldgomb.jpg"));
x=2;
}else if (x==2) {
A1.setIcon(new ImageIcon("sargagomb.jpg"));
x=1;
} }
event.getSource()
返回对your的引用JLabel
,您可以使用类似next的方法:
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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句