Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a value when JButton Is Pressed

I've been trying to learn java for about a week now yet I've been stuck with one bug. This is supposed to increment the variable "clicks" by 1 every time the button is pressed but I keep getting the same error:

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


public class Testclass {

    private JFrame frame;
    private JPanel panel;
    private JButton button1;
    private JLabel label;


    public Testclass () {

        gui();

    }

    public void gui () { 

        final int clicks = 0;

        frame = new JFrame("Test");
        frame.setVisible(true);
        frame.setSize(600,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        panel.setBackground(Color.cyan);

        button1 = new JButton("Test");
        label = new JLabel("Button Click Count: ");

        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                clicks++;
                label.setText("Click Count: " +clicks);

            }


        });

        panel.add(label);
        panel.add(button1);

        frame.add(panel);



    }

    public static void main (String[] args) {

        new Testclass();


    }

}

It keeps giving me an error on line 42, where "clicks" is incremented "Multiple Markers at this line" any help is appreciated. thanks, jack

like image 314
user3132022 Avatar asked Mar 22 '26 03:03

user3132022


1 Answers

  final int clicks = 0;

make clicks as a instance member. Nowit is final you cannot increment it.

If you remove final in the current place you cannot access inside the actionPerformed, So make it as instance member.

public class Testclass {

   private int clicks = 0;
like image 149
Suresh Atta Avatar answered Mar 24 '26 16:03

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!