如何在panelResult [i] .addMouseListener中获取mouseEntered的“for循环”中使用的“i”变量?谢谢!
buttonCategory[0].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//hidden codes here...
panelCategory.remove(scrollPane);
panelCategory.add(scrollPane);
panelArray.removeAll();
panelResult = new JPanel[totalCount];
int y = 0;
for(int i = 0; i < panelResult.length; i++){
panelResult[i] = new JPanel();
panelResult[i].setLayout(null);
panelResult[i].setBackground(new Color(27, 182, 32));
panelResult[i].setBounds(0, y, 730, 200);
panelArray.add(panelResult[i]);
//hidden codes here...
panelResult[i].add(labelArrayResult);
panelResult[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
panelResult[0].setBackground(Color.BLACK);
//if i change it to panelResult[i].setBackground(Color.BLACK); the "i" will be the error. i want to get the value of i from the panelResult[i].
revalidate();
repaint();
}
});
}
revalidate();
repaint();
}
revalidate();
repaint();
}
});
我打算将它用于mouseClicked和mouseExited。它是一个结果列表,这就是为什么它全部排列和循环。
我得到的例外是:
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: 7
at ph.edu.tip.cpedepartment.cpepds.ProjectDesignPage$1$1.mouseEntered(ProjectDesignPage.java:233)
此外,面板的数量来自数据库的总数,这就是我需要使用索引的原因。再次感谢!
答案 0 :(得分:1)
我相信你可以使用MouseEvent的源来获取事件的来源:
public void mouseEntered(MouseEvent e) {
((JPanel)e.getSource()).setBackground(Color.BLACK);
//the index here is the error
revalidate();
repaint();
}
如果这不起作用,我会尝试:
for(int i = 0; i < panelResult.length; i++){
//some hidden codes here...
final JPanel panel = panelResult[i];
panel.add(labelArrayResult);
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
panel.setBackground(Color.BLACK);
//the index here is the error
revalidate();
repaint();
}
});
}
答案 1 :(得分:1)
问题是,为什么首先想要i
?您想要实际的索引值,还是希望panelResult
在索引i
?如果它只是你想要的panelResult
,请接受Eran的回答。
否则,您可以将i
值复制到侦听器的成员变量中,如下所示:
for (int i = 0; i < panelResult.length; i++) {
final int finalI = i;
// some hidden codes here...
panelResult[i].add(labelArrayResult);
panelResult[i].addMouseListener(new MouseAdapter() {
private int innerI = finalI;
@Override
public void mouseEntered(MouseEvent e) {
panelResult[innerI].setBackground(Color.BLACK);
revalidate();
repaint();
}
});
}
finalI
innerI