java变量范围如何设置,Java:在封闭范围内定义的局部变量mi必须是最终的或有效的最终...

I get the error, as in subject, and I kindly ask you how to repair it...

ERROR is in menuItem-loop, where I try to set the textArea foreground colour to one picked from menuItem: (colors[mi])

String[] colors = {

"blue",

"yellow",

"orange",

"red",

"white",

"black",

"green",

};

JMenu mnForeground = new JMenu("Foreground");

for (int mi=0; mi

String pos = Character.toUpperCase(colors[mi].charAt(0)) + colors[mi].substring(1);

JMenuItem Jmi =new JMenuItem(pos);

Jmi.setIcon(new IconA(colors[mi]));

Jmi.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

JMenuItem item = (JMenuItem) e.getSource();

IconA icon = (IconA) item.getIcon();

Color kolorIkony = getColour(colors[mi]); // ERROR HERE: (colors[mi])

textArea.setForeground(kolorIkony);

}

});

mnForeground.add(Jmi);

}

public Color getColour(String colour){

try {

kolor = Color.decode(colour);

} catch (Exception e) {

kolor = null;

}

try {

final Field f = Color.class.getField(colour);

kolor = (Color) f.get(null);

} catch (Exception ce) {

kolor = Color.black;

}

return kolor;

}

解决方案

The error means you cannot use the local variable mi inside an inner class.

To use a variable inside an inner class you must declare it final. As long as mi is the counter of the loop and final variables cannot be assigned, you must create a workaround to get mi value in a final variable that can be accessed inside inner class:

final Integer innerMi = new Integer(mi);

So your code will be like this:

for (int mi=0; mi

String pos = Character.toUpperCase(colors[mi].charAt(0)) + colors[mi].substring(1);

JMenuItem Jmi =new JMenuItem(pos);

Jmi.setIcon(new IconA(colors[mi]));

// workaround:

final Integer innerMi = new Integer(mi);

Jmi.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

JMenuItem item = (JMenuItem) e.getSource();

IconA icon = (IconA) item.getIcon();

// HERE YOU USE THE FINAL innerMi variable and no errors!!!

Color kolorIkony = getColour(colors[innerMi]);

textArea.setForeground(kolorIkony);

}

});

mnForeground.add(Jmi);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值