简体   繁体   English

在内部类(java)中访问局部变量

[英]local variable is accessed within inner class (java)

I got two errors after I compiled my code. 编译完代码后,我遇到了两个错误。

The errors are: 错误是:

1. 1。

  local variable input is accessed within inner class; 
  needs to be declared final
     String name = input.getText();

2. 2。

  local variable c_age is accessed within inner class; 
  needs to be declared final
     Object child_age = c_age.getSelectedItem();

This is my code: 这是我的代码:

import javax.swing.*;
import java.awt.event.*;

public class GUI
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Try GUI");
        JLabel l1 = new JLabel("Please Enter Your Child's Name");
        JTextField input = new JTextField("",10);

        JLabel l2 = new JLabel("Choose Your Child's Age");
        String[] age = {"Age","1","2","3","4","5","6"};
        JComboBox c_age = new JComboBox(age);

        JButton button = new JButton("Search");

        JTextArea result = new JTextArea();
        JScrollPane extend_area = new JScrollPane(result);

        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                String name = input.getText();
                Object child_age = c_age.getSelectedItem();
            }
        });

        JPanel panel = new JPanel();
        panel.add(l1);
        panel.add(input);
        panel.add(l2);
        panel.add(c_age);
        panel.add(button);
        panel.add(extend_area);
        frame.add(panel);
        frame.setSize(350,350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

}

How can I solve this error? 我该如何解决这个错误?

You need to declare 你需要申报

JTextField input = new JTextField("",10);

and

JComboBox c_age = new JComboBox(age);

like this: 像这样:

final JTextField input = new JTextField("",10);

final JComboBox c_age = new JComboBox(age);

This means that input and c_age cannot change: 这意味着inputc_age不能更改:

Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class. 任何在内部类中使用但未声明的局部变量必须在内部类的主体之前明确赋值。

Explanation taken from The Java Language Specification, Section - 8.1.3 Inner Classes and Enclosing Instances 从Java语言规范, 第8.1.3节内部类和封闭实例中获取的解释

If you declare the variables as an final then it will solve your errors but according to me its not the good solution for the problem. 如果你将变量声明为final,那么它将解决你的错误,但据我所知它不是解决问题的好方法。 Similar problem has discussed here you can have a look here for more understanding. 这里讨论过类似的问题,你可以看看这里有更多的了解。

In solution to yours problem you can have define methods by using them you can get better solution. 在解决您的问题时,您可以通过使用它们来定义方法,您可以获得更好的解决方案。 For hint you can read How to access non-final local variable inside anonymous inner class 有关提示,您可以阅读如何访问匿名内部类中的非最终局部变量

Any variable that you use inside the actionPerformed method of your inner class will need to be declared final. 您在内部类的actionPerformed方法中使用的任何变量都需要声明为final。 Try the following: 请尝试以下方法:

import javax.swing.*;
import java.awt.event.*;

    public class GUI
    {
        public static void main(String[] args)
        {
            JFrame frame = new JFrame("Try GUI");
            JLabel l1 = new JLabel("Please Enter Your Child's Name");
            final JTextField input = new JTextField("",10);

            JLabel l2 = new JLabel("Choose Your Child's Age");
            String[] age = {"Age","1","2","3","4","5","6"};
            final JComboBox c_age = new JComboBox(age);

            JButton button = new JButton("Search");

            JTextArea result = new JTextArea();
            JScrollPane extend_area = new JScrollPane(result);

            button.addActionListener(new ActionListener()
            {
                    public void actionPerformed(ActionEvent ae)
                    {
                        String name = input.getText();
                        Object child_age = c_age.getSelectedItem();


                    }
            });

            JPanel panel = new JPanel();
            panel.add(l1);
            panel.add(input);
            panel.add(l2);
            panel.add(c_age);
            panel.add(button);
            panel.add(extend_area);
            frame.add(panel);
            frame.setSize(350,350);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }

    }

As adding final takes away a lot of flexibility, I'd like to suggest the following: create an accessor method, which is encouraged anyway. 由于添加final会带来很大的灵活性,我想建议如下:创建一个访问器方法,无论如何都是鼓励的。 But this is mostly useful when dealing with objects, while in your case everything is static. 但这在处理对象时非常有用,而在你的情况下,一切都是静态的。 Therefore, this answer might not apply to your specific situation, but because googling for your error message yields this question as the top result, I think an alternative that's applicable in most cases (using objects is more common than doing everything from a static method) should be present here as well. 因此,这个答案可能不适用于您的具体情况,但因为谷歌搜索您的错误消息产生这个问题作为最重要的结果,我认为在大多数情况下适用的替代方案(使用对象比从静态方法做任何事情更常见)也应该出现在这里。

public class MyClass extends MySuperClass {
    private MyPropertyClass aProperty;

    public MyClass() {
        new JButton().setActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // aProperty.aMethod(); -- Bang! That should be final, the compiler says.
                getMyProperty().aMethod(); // -- Everything okay, works fine, no compiler complaints.
            }
        });
    }

    public getMyProperty() {
        return aProperty;
    }
}

I just created a temporary var in the main class eg 'tempString' and then it can be set to the var that's causing the problem. 我刚刚在主类中创建了一个临时var,例如'tempString',然后它可以设置为导致问题的var。 So: 所以:

tempString = myString

that way I can call tempString without any problem at all. 这样我就可以毫无问题地调用tempString。 Check my example below: 查看下面的示例:

// Create my temp var here
private String tempUrl;

// my function here
public void updatePage(String url)
{
    // Can use 'url' here because it's not within inner class
    if(!url.equals(""))
    {
        // Set 'tempUrl' to 'url' so I can use it without problem
        tempUrl = url;

        // My inner class that used to cause the problem
        backgroundUpdate = new Thread(new Runnable()
        {
            // From here on I use 'tempUrl' to solve the problem
            public void run()
            {
                // Do something with 'tempUrl' here (where 'url' used to be used)
            }
        });

        backgroundUpdate.start();
    }
}

The JTextField named input was declared inside of the main method. JTextField命名输入是在main方法内声明的。 You should probably do something like this: 你应该做这样的事情:

  public class GUI{

      //declare all your components here e.g.

      JTextField input;

      public static void main(String args[]){
              new GUI();
      }

      public GUI(){
          //instantiate components here
          input = new JTextField();
          //and so on.
      }

  }

That way the reference to input inside the inner class will give no problems. 这样,对内部类中的输入的引用将不会产生任何问题。

You have to declare final the two variables you're accesing: input and c_age . 您必须声明final的两个变量: inputc_age

If you don't want to do this, then you can either create a new proper class (not an ad-hoc one) and pass those as parameters in the constructor, or (I did this when working with GUIs in Java) create a listener class that takes objects in its constructor and makes them available locally, then ad-hoc instantiate that. 如果您不想这样做,那么您可以创建一个新的正确类(而不是ad-hoc类)并将它们作为参数传递给构造函数,或者(我在使用Java中的GUI时这样做)创建一个在其构造函数中获取对象并使它们在本地可用的侦听器类,然后临时实例化该对象。

The input variable and the c_age variable disappears after the method execution is completed. 方法执行完成后,输入变量和c_age变量消失。 You wont be allowed to use these variables inside the local inner classes unless it is final. 除非是最终的,否则不允许在本地内部类中使用这些变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从内部类内部访问局部变量 - Local variable is accessed from within inner class 错误:从内部类访问局部变量 imagesLabel; 需要声明为 final (Java) - Error: local variable imagesLabel is accessed from within inner class; needs to be declared final (Java) 从内部类内部访问的Java局部变量; 需要声明为final,为什么它可以在NetBeans中工作? - Java local variable accessed from within inner class; needs to be declared final, why it works in NetBeans? 在内部类修订中访问局部变量“ i”? - Local variable “i” is accessed within an inner class fix? 内部类中访问的变量 - variable accessed within inner class Java-从内部类内部访问变量 - Java - Variable is being accessed from within inner class java:从内部类内部访问局部变量循环器; 需要声明为final,但是变量可能尚未初始化 - java: local variable looper is accessed from within inner class; needs to be declared final, but then variable might not have been initialized 从内部类中访问变量 - Variable is accessed from within inner class 从内部类内部访问LibGDX变量 - LibGDX variable accessed from within inner class 从另一个内部 class 内部的内部 class 内部访问变量 - Variable is accessed from within inner class inside another inner class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM