Java Action Listener不使用数组

时间:2014-05-17 22:52:38

标签: java swing actionlistener

这段代码有什么问题?当我点击按钮时,我试图将它转到下一个名为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]);
    }});

但如果我宣布它是最后的那个排序它的行告诉我把最后的声明拿出来。

这里是最终声明的错误:

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

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

2 个答案:

答案 0 :(得分:3)

试试这个:

Book[] bk = new Book[5];
// fill bk here
final Book[] bkSorted = sortArray(bk);

答案 1 :(得分:0)

  1. 您正在尝试运行无法编译的代码。您不希望这样做,而是希望在开发的编译阶段修复所有编译问题。
  2. 您可以将bk设为类的非最终实例字段而不是局部变量,问题就解决了。