I can’t do a click counter on a Jbutton

Asked

Viewed 909 times

2

I am developing a "game" where there is a button on the screen and the player has to click several times on the button to make money. For that, I’m doing a sort of click counter, where the variable xi is the amount of clicks, and the amount of clicks is equivalent to the money the player has.

The problem is that when I click once on the button, the variable xi passes to one, as it is supposed to, but then the counter stops counting clicks (as if the click limit was 1. How do I change the click limit to infinity?

And I’m not using netbeans to create the window, I’m doing everything in code.

package getRich;


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class rich extends JFrame{


    private JLabel label;
    private JButton button;
    private JLabel label1;

    public rich() {

        setLayout(new FlowLayout());

        label1 = new JLabel("Hey!! Wellcome to get rich!! The game is simple... GET RICH!");
        add(label1);

        label = new JLabel("Your money: 0");
        add(label);


        button = new JButton("Click me to get MONEY!!");
        add(button);


        but but = new but();
        button.addActionListener(but);

    }


    public class but implements ActionListener{
        int xi = 0;
        public void actionPerformed(ActionEvent but){


            for(xi=0; xi<=1; xi++){
            label.setText("Your money: " + xi);
            }

        }

    }


    public static void main(String[] args) {        

    rich gui = new rich();

    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setVisible(true);
    gui.setSize(500, 500);
    gui.setTitle("Get Rich");


    }

}

1 answer

1


And change your Istener method to:

class but implements ActionListener{

    private int xi;

    @Override
    public void actionPerformed(ActionEvent but){

        xi++;
        label.setText("Your money: " + xi);

    }

}

Note also the java naming convention, where classes should start with uppercase.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.