access to variable within inner class in java

后端 未结 5 1771
陌清茗
陌清茗 2020-12-10 02:36

I\'m trying to create an array of JLabels, all of them should go invisible when clicked. The problem comes when trying to set up the mouse listener through an inner class th

5条回答
  •  一向
    一向 (楼主)
    2020-12-10 02:45

    Your local variable must be final to be accessed from the inner (and anonymous) class.

    You can change your code for something like this :

    for (int i = 1; i < label.length; i++) {
        final JLabel currentLabel =new JLabel("label " + i); 
        currentLabel.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                currentLabel.setVisible(false);   // No more compilation error here
            }
        });
        label[i] = currentLabel;
    }
    

    From the JLS :

    Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

    Any local variable used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.


    Resources :

    • JLS - Inner Classes and Enclosing Instances

提交回复
热议问题