我有一个带有 JPanels 的 2D 数组,我想在数组中的每个 JPanel 中添加一个 mouseListener,所以我使用 2 个 for 循环来添加它们,但我想传递我在每个 mouseListener 中的 for 循环中使用的变量,但是当我尝试让所有 mouseListener 都具有与最后一个 for 循环中使用的最后一个变量相同的值。那么我做错了什么?
这是我的代码:
for (i=0 ; i<3; i++) {
for (k=0; k<3; k++) {
a[i][k].addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
temp = a[i-1][k];
a[i-1][k] = a[i][k];
a[i][k] = temp;
//some
//code here
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e)
{
invalidate();
revalidate();
repaint();
}
public void mouseEntered (MouseEvent e)
{}
public void mouseExited (MouseEvent e) {
}
});
}
}
我只需要知道是否有办法将变量 i,k 作为 mouseListener 的参数传递给 mouselistener
最佳答案
您只能将 final
局部变量和类字段传递给匿名方法。
我建议创建一个实现 MouseAdapter
的新类,该类将数组和适当的索引作为构造函数中的参数。然后,您可以将它们保存为类中的字段,并在调用 MouseEvent
时使用它们。
如果您需要访问此处未提及的其他变量,您始终可以将它们传递到这个新类的构造函数中。
代码:
public AppletMouseListener extends MouseAdapter {
private final JApplet theApplet;
private final Container[][] a;
private final int i;
private final int j;
public AppletMouseListener(JApplet theApplet, Container[][] a, int i, int k) {
this.theApplet = theApplet;
this.a = a;
this.i = i;
this.k = k;
}
@Override
public void mousePressed(MouseEvent e) {
JComponent temp = a[i-1][k];
a[i-1][k] = a[i][k];
a[i][k] = temp;
//some
//code here
}
@Override
public void mouseReleased(MouseEvent e) {
theApplet.invalidate();
theApplet.revalidate();
theApplet.repaint();
}
}
关于java - 将 mouseListener 添加到 JPanel 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16224752/