0

I am making a simple program where the user clicks a button and a label displays the number of clicks. This is what I have so far:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class mainGUI {

    public static void main(String[] args) {

        int numOfClicks = 0;

        JFrame mainWindow = new JFrame("ClickerCounter");
        JPanel mainPanel = new JPanel();
        JButton clickerBtn = new JButton("Click Here");
        JButton clickerReset = new JButton("Reset");
        JLabel mainLabel = new JLabel("You have clicked 0 times.");

        mainWindow.setPreferredSize(new Dimension(400,75));
        mainWindow.pack();
        mainWindow.setLocationRelativeTo(null);
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        mainPanel.add(clickerBtn);
        mainPanel.add(clickerReset);
        mainPanel.add(mainLabel);
        mainWindow.add(mainPanel);

        mainWindow.setVisible(true);

        clickerBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                numOfClicks += 1;

            }
        }); 
    }
}

I declared the numOfClicks variable inside the main method, but I get "Local variable numOfClicks defined in an enclosing scope must be final or effectively final". How can I make the numOfClicks variable accessible by the anonymous ActionListener class?

I can't make this variable final as the numOfClicks will be changing throughout the usage of the program.

Psear
  • 105
  • 8
  • Make it a field, not a local variable. – Hovercraft Full Of Eels Nov 04 '17 at 15:04
  • To follow up on what @HovercraftFullOfEels said. Anonymous classes cannot access local 'non-final' variables like you've done. Make the numOfClicks variable an instance variable and it should work. Here's some other answers on this type of question https://stackoverflow.com/questions/4732544/why-are-only-final-variables-accessible-in-anonymous-class – Oskarzito Nov 04 '17 at 15:09

0 Answers0