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.