我有一个标签[][],其中的所有标签都有鼠标适配器,当任何鼠标监听器触发时我想到达所有标签。所有标签都有一个图标。如果我点击其中一个,所有标签都应该更改其图标。
我的代码示例:
for(int x = 1; x < 11; x++){
for(int y = 1; y < 11; y++){
label[x][y].setIcon(korok[randomGenerator.nextInt(6)]);
label[x][y].addMouseListener(new LabelMouseListener(x, y));}}
}
}
public class LabelMouseListener extends MouseAdapter{
private final int x, y;
public LabelMouseListener() {
this.x = x;
this.y = y;
}
@Override
public void mouseClicked(MouseEvent e) {
int egyklik[] = new int[3];
if(egyklik[0] == 0){
egyklik[0] = 1; egyklik[1] = x; egyklik[2] = y;
}
else if(egyklik[0] == 1){
//JLabel l = (JLabel) e.getSource();
// it's wrong code, i would like something what will do this,
//if i do the Override in the other(JFrame) class, it can
//reach labels, but can't use x and y
//label[x][y].setIcon(label[egyklik[1]][egyklik[2]].getIcon());
//label[egyklik[1]][egyklik[2]].setIcon(label[x][y].getIcon());
}
}
}
最佳答案
是的,您可以访问所有标签。
为什么你从index 1.
开始请参阅您的 for 循环( int x = 1 and int y = 1
)。
我认为 x 和 y 以 index 0
开头.
x < 11; and y< 11;
需要更改为x < 10;and y < 10;
分别。
在你的 mouseClicked() 方法中这样做。
JLabel l = null;
if(e.getSource() instanceof JLabel){
l = (JLabel) e.getSource();
}
关于java - 我可以使用 mouselistener/mouseadapter 访问 label[][] 中的所有标签吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20454617/