[英]add mouseListener to an array of JPanels
我有一個帶有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傳遞給mouselisteners作為mouseListener的參數
您只能將final
局部變量和類字段傳遞給匿名方法。
我建議創建一個實現MouseAdapter
的新類, 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();
}
}
如果使用普通(命名)類而不是匿名類,則代碼將更清晰。 然后你可以將相關的東西( a
, i
和k
)傳遞給構造函數。
匿名類不能有構造函數,但它們可以訪問聲明為final
局部變量。
for (int ii=0 ; ii<3; ii++) {
for (int kk=0; kk<3; kk++) {
final int i = ii;
final int k = kk;
a[i][k].addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
JPanel temp = a[i-1][k]; // index out of bounds
a[i-1][k] = a[i][k];
a[i][k] = temp;
}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e)
{
invalidate();
revalidate();
repaint();
}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.