gpt4 book ai didi

java - 如何将 "for loop"中的变量值用于 mouseEntered?

转载 作者:行者123 更新时间:2023-11-30 03:27:23 25 4
gpt4 key购买 nike

如何获取 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)是:

Exception in thread "AWT-EventQueue-0" 
java.lang.ArrayIndexOutOfBoundsException: 7
at ph.edu.tip.cpedepartment.cpepds.ProjectDesignPage$1$1.mouseEntered(ProjectDesign‌​Page.java:233)

此外,面板的数量来自数据库的总数,这就是我需要使用索引的原因。再次感谢!

最佳答案

我相信您可以使用鼠标事件源来获取事件的来源:

                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();
}

});

}

关于java - 如何将 "for loop"中的变量值用于 mouseEntered?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29862698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com