Java:在封闭范围内定义的局部变量mi必须是最终的或有效的最终 [英] Java: Local variable mi defined in an enclosing scope must be final or effectively final
问题描述
我得到了错误,就像在主题中一样,我恳请你如何修复它...
ERROR在menuItem-loop中,我尝试将textArea前景色设置为从menuItem中选择的颜色: (colors [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<colors.length; 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;
}
推荐答案
错误表示你不能在内部类中使用局部变量 mi
。
The error means you cannot use the local variable mi
inside an inner class.
要在内部类中使用变量,必须声明它 final
。只要 mi
是循环的计数器并且 final
变量无法分配,您必须创建一个变通方法来获取 mi
可以在内部类中访问的 final
变量中的值:
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<colors.length; 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);
}
}
这篇关于Java:在封闭范围内定义的局部变量mi必须是最终的或有效的最终的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!