背景

在以下屏幕截图中,用户应该能够通过单击单选按钮之一来更改图像:

java - 错误:从内部类内部访问局部变量imagesLabel;需要声明为final(Java)-LMLPHP

单击单选按钮时,图片应更改为另一张图片。
我已将所有图像放入一个数组。

问题

到目前为止,我在尝试编译代码时(请参见下面的源代码),编译器给出以下错误:


  错误:从内部类内部访问局部变量imagesLabel;需要宣布为最终


并且在各个变量之前添加final时,在编译时出现以下错误:


  错误:预期为


Java代码(添加final之后)

Icon[] images = new Icon[3];

// Get the images and store them in the images array.  These images
// were manually resized to be similar in size prior to writing the
// program.
images[0] = new ImageIcon("/Users/grimygod/Desktop/negativeFilterExample.png");
images[1] = new ImageIcon("/Users/grimygod/Desktop/reflect.png");
images[2] = new ImageIcon("/Users/grimygod/Desktop/colorSubtraction.png");

// The images will be displayed as the image on a JLabel without text
JLabel imagesLabel = new JLabel();

// Set the initial image to be the negative filter, and add it to the panel,
// since the radio button for the negative filter is initially selected.
imagesLabel.setIcon(images[0]);
iconPanel.add(imagesLabel);
radioButtonPanel.add(iconPanel);

// Creation of "Select An Image & Apply Filter!" button
JButton selectButton = new JButton("Select An Image & Apply Filter!");
submitButtonPanel.add(selectButton);
radioButtonPanel.add(submitButtonPanel);

// Makes the whole window visible
testFrame.setVisible(true);

// First button is selected when program is ran
button1.setSelected(true);

button1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        final imagesLabel.setIcon(images[2]);   //  <<<<< ERROR in this line
   }
});

最佳答案

您可以执行以下任一操作来解决此问题:

A.将imagesLabel声明为final

final JLabel imagesLabel = new JLabel();


B.将imagesLabel声明为实例变量,即方法之外。换句话说,在类本身中声明它。

确保从final中删除​​final imagesLabel.setIcon(images[2]);,即应该只是imagesLabel.setIcon(images[2]);

关于java - 错误:从内部类内部访问局部变量imagesLabel;需要声明为final(Java),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59147293/

10-09 13:17