本文介绍了局部变量需要声明为final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误从内部类内部访问局部变量框;需要声明为final".看起来不错,但是我并不真正认为这是最好的解决方案,所以我希望也许有人可以帮助我.这是我的代码:

I'm receiving the error "local variable box is accessed from within inner class; needs to be declared final". That seems alright, but I don't really think it's the best solution, so I was hoping maybe someone else can help me out. Here is my code:

public void showPublisherBox(JComboBox box) {
    if (publisherBox == null) {
        publisherBox = new AddPublisherForm();
        publisherBox.setLocationRelativeTo(this);
    }
    publisherBox.addWindowListener(new WindowAdapter()
    {
    public void windowClosing(WindowEvent we)
    {
        this.populatePublishers(box);
    }

        private void populatePublishers(JComboBox box){
            box.setModel(db.getPublishers());
        }
    });
    publisherBox.setVisible(true);
}

Publisher表单只是一个新的JFrame,它会打开并接收一些信息,当它关闭时,我希望通过设置db.getPublishers()方法中的模型来重新填充JComboBox.

Publisher form is just a new JFrame that opens up and takes in some information, and when it's closed I want the JComboBox to be repopulated via setting the model from my db.getPublishers() method.

那么,有什么更好的方法可以做我在这里做的事情,还是我必须声明一些最终内容?

So is there a better way to do what I'm doing here, or am I going to have to declare something as final?

谢谢

推荐答案

由于您没有在外部代码中修改box,因此使用final恰好是正确的解决方案问题.对您自己(和对编译器)的保证是,box的值在封闭范围内不会改变.编译器会告诉您是否违反了诺言.

Since you're not modifying box in the outer code, using final is exactly the correct way to solve this problem. It's a promise to yourself (and to the compiler) that the value of box won't change in the enclosing scope. The compiler will tell you if you break that promise.

使用final没有编译时间或运行时成本.

There is no compile time or runtime cost to using final.

这篇关于局部变量需要声明为final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 20:46
查看更多