java 创建JButton[][] 无法解决单个按钮监听???
JButton[][] button=new JButton[11][11];
public void init()
{
int i = 0,j=0;
setLayout(new GridLayout(10,10));
for(;i <10;i++)
{
j=0;
for(;j <10;j++)
{
button[i][j]=new JButton(unknownIcon);
add(button[i][j]);
button[i][j].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e)
{
***button[i][j].setIcon(openIcon);
}
});
***标注那一行提示:不能引用另一方法中定义的内部类中非终态变量 i
而将ij放到init外后***button[i][j].setIcon(openIcon);调用ij时ij的值永远是0
急救 (具体我就是想实现创建一个按钮组 并且每个按钮有单独的监听 而监听结果是相同的)
[解决办法]
button[i][j].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
((JButton)e.getSource()).setIcon(openIcon);
}
if (e.getButton() == MouseEvent.BUTTON3) {
((JButton)e.getSource()).setIcon(flagIcon);
}
}
});
帮你改好了