I can not do a click counter on a JButton

2

I'm developing a "game" where there is a button on the screen and the player has to click the button several times to make money. For this, I'm doing a kind of click counter, where%% is the number of clicks, and the number of clicks is equivalent to the money the player has.

The problem is that when I click the button once, the variable xi changes to a, as it is supposed to, but then the counter stops counting the clicks (as if the click limit was 1. How is it 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");


    }

}
    
asked by anonymous 16.06.2016 / 17:41

1 answer

1

And change your listener method to:

class but implements ActionListener{

    private int xi;

    @Override
    public void actionPerformed(ActionEvent but){

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

    }

}

Also note the java naming convention, where classes should start with a capital letter.

    
16.06.2016 / 17:51