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

sinafarheidar12 :

Background

On following screenshot, the user should be able to change the image by clicking on one of the radio buttons:

screenshot

When a radio button is clicked the picture should change to a different one . I have put all images into an array.

Problem

When compiling code I have tried so far (see source below) the compiler gives following error:

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

And once I add final before respective variable, I got following error when compiling:

Error: <identifier> expected

Java Code (after adding the 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 
   }
});
Arvind Kumar Avinash :

You can do any of the following to resolve the issue:

A. Declare imagesLabel as final

final JLabel imagesLabel = new JLabel();

B. Declare imagesLabel as an instance variable i.e. outside the method. In other words, declare it in the class itself.

Make sure to remove final from final imagesLabel.setIcon(images[2]); i.e. it should be simply imagesLabel.setIcon(images[2]);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356750&siteId=1