gpt4 book ai didi

java - 错误: local variable imagesLabel is accessed from within inner class; needs to be declared final (Java)

转载 作者:太空宇宙 更新时间:2023-11-04 09:14:59 32 4
gpt4 key购买 nike

背景

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

screenshot

单击单选按钮时,图片应更改为不同的图片。我已将所有图像放入数组中。

问题

当编译我迄今为止尝试过的代码时(请参阅下面的源代码),编译器给出以下错误:

Error: local variable imagesLabel is accessed from within inner class; needs to be declared final

一旦我在相应变量之前添加 final ,编译时就会出现以下错误:

Error: <identifier> expected

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 imagesLabel.setIcon(images[2]); 中删除 final,即它应该只是 imagesLabel.setIcon(images[2]);

关于java - 错误: local variable imagesLabel is accessed from within inner class; needs to be declared final (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59147293/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com