zoukankan      html  css  js  c++  java
  • java 更换皮肤问题Cannot refer to a nonfinal variable inside an inner class defined in a different method

    遇到一个很奇怪的错误,想为动态生成的菜单项增加事件处理。大致代码如下:

    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

  • 相关阅读:
    345. Reverse Vowels of a String
    344. Reverse String
    125. Valid Palindrome
    67. Add Binary
    28. Implement strStr()
    20. Valid Parentheses
    14. Longest Common Prefix
    670. Maximum Swap
    2017济南北大青鸟accp和学士后课程的真实情况
    2017济南北大青鸟accp和学士后课程的真实情况
  • 原文地址:https://www.cnblogs.com/youxin/p/3138225.html
Copyright © 2011-2022 走看看