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

发布于 2024-11-01 02:46:17 字数 1711 浏览 1 评论 0原文

编译代码后出现两个错误。

错误是:

1.

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

2.

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

这是我的代码:

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);
    }

}

我该如何解决此错误?

I got two errors after I compiled my code.

The errors are:

1.

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

娇纵 2024-11-08 02:46:17

您需要像这样声明

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

JComboBox c_age = new JComboBox(age);

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

final JComboBox c_age = new JComboBox(age);

意味着 inputc_age 不能更改:

任何局部变量,已使用但未使用
在内部类中声明的必须是
在之前明确分配
内部类的主体。

解释取自 Java 语言规范 部分 - 8.1.3 内部类和封闭实例

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:

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

感性 2024-11-08 02:46:17

如果您将变量声明为最终变量,那么它将解决您的错误,但根据我的说法,这不是问题的良好解决方案。类似的问题已经在这里讨论过,你可以看看此处以获取更多理解。

在解决您的问题时,您可以定义方法,通过使用它们可以获得更好的解决方案。如需提示,您可以阅读
如何访问匿名内部类中的非final局部变量

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. 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

时光瘦了 2024-11-08 02:46:17

您在内部类的 actionPerformed 方法中使用的任何变量都需要声明为 Final。请尝试以下操作:

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);
        }

    }

Any variable that you use inside the actionPerformed method of your inner class will need to be declared 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);
        }

    }
怪我太投入 2024-11-08 02:46:17

由于添加 final 会失去很大的灵活性,因此我建议如下:创建一个访问器方法,无论如何都鼓励这样做。但这在处理对象时最有用,而在您的情况下,一切都是静态的。因此,这个答案可能不适用于您的具体情况,但因为谷歌搜索您的错误消息会产生这个问题作为最佳结果,我认为在大多数情况下都适用的替代方案(使用对象比从静态方法执行所有操作更常见)也应该出现在这里。

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;
    }
}

As adding final takes away a lot of flexibility, I'd like to suggest the following: create an accessor method, which is encouraged anyway. 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;
    }
}
四叶草在未来唯美盛开 2024-11-08 02:46:17

名为 input 的 JTextField 是在 main 方法内部声明的。您可能应该这样做:

  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.
      }

  }

这样,对内部类中的输入的引用就不会出现问题。

The JTextField named input was declared inside of the main method. 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.

征棹 2024-11-08 02:46:17

您必须声明您要访问的两个变量finalinputc_age

如果您不想这样做,那么您可以创建一个新的适当类(不是临时类)并将它们作为构造函数中的参数传递,或者(我在使用 Java 中的 GUI 时这样做)创建一个监听器类在其构造函数中获取对象并使它们在本地可用,然后临时实例化该对象。

You have to declare final the two variables you're accesing: input and c_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.

绝不放开 2024-11-08 02:46:17

输入变量和c_age变量在方法执行完成后消失。除非它是最终的,否则您将不被允许在本地内部类中使用这些变量。

The input variable and the c_age variable disappears after the method execution is completed. You wont be allowed to use these variables inside the local inner classes unless it is final.

蓝眸 2024-11-08 02:46:17

我刚刚在主类中创建了一个临时变量,例如“tempString”,然后可以将其设置为导致问题的变量。所以:

tempString = myString

这样我就可以毫无问题地调用 tempString 了。检查我下面的例子:

// 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();
    }
}

I just created a temporary var in the main class e.g 'tempString' and then it can be set to the var that's causing the problem. So:

tempString = myString

that way I can call tempString without any problem at all. 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();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文