遇到一个很奇怪的错误,想为动态生成的菜单项增加事件处理。大致代码如下:
public class MainMenu extends JFrame implements ActionListener{ private String[] themes={"SubstanceAutumnLookAndFeel","SubstanceBusinessLookAndFeel"}; public MainMenu() { String[] themes={"SubstanceAquaTheme","SubstanceBarbyPinkTheme"}; JMenuItem[] menuItems=new JMenuItem[themes.length]; for( int i=0;i<themes.length;i++) { menuItems[i]=new JMenuItem(themes[i]); skinMenu.add(menuItems[i]); menuItems[i].addActionListener( new ActionListener() { int type=i;报错 public void actionPerformed(ActionEvent e) { changeSkin(type); } }); } } public void changeSkin(int type) { try { UIManager.setLookAndFeel("org.jvnet.substance.skin."+themes[type]); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { // TODO Auto-generated catch block e.printStackTrace(); } SwingUtilities.updateComponentTreeUI(this); } }
Cannot refer to a non-final variable inside an inner class defined in a different method ,change i to final。
要我改为final类型。报错原因是java不支持闭包。函数内的函数不能引用外部变量。怎么解决这个问题看下一篇
http://www.cnblogs.com/youxin/archive/2013/06/16/3138238.html
参考办法:http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-differen