繁体   English   中英

Java Action Listener不适用于数组

[英]Java Action Listener not working with array

此代码有什么问题? 当我单击按钮时,我试图将其转到名为bk的下一个排序数组。

Book[] bk = new Book[5];
bk = sortArray(bk);
final JTextArea textArea = new JTextArea();

JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        for (int i = 0; i < bk.length; i++)
            textArea.append("\n" + bk[i+1]);
    }});

但是,如果我将其声明为final,则对其进行排序的行会告诉我将final声明删除。

这里的错误与最终声明:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The final local variable bk cannot be assigned. It must be blank and not using a compound assignment

而且没有最终声明:

Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problems: 
Cannot refer to a non-final variable bk inside an inner class defined in a different method
Cannot refer to a non-final variable bk inside an inner class defined in a different method

我该怎么做才能解决此问题?

尝试这个:

Book[] bk = new Book[5];
// fill bk here
final Book[] bkSorted = sortArray(bk);
  1. 您正在尝试运行无法编译的代码。 您不想这样做,而是想在开发的编译阶段解决所有编译问题。
  2. 您可以将bk设为该类的非最终实例字段,而不是局部变量,从而解决了该问题。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM