user3770144
user3770144

Reputation: 105

The count number of pressed button

I need that when I press the button to show me how many times was the button pressed. I use this method, but on console still show me the number 1.

Here is code:

 button_help.setOnMousePressed(new EventHandler<MouseEvent>() {

    @Override
    public void handle(MouseEvent event) {

    int count = 0;
    count ++;

        System.out.println(count);
    }


 });

Upvotes: 1

Views: 8012

Answers (3)

Frunk
Frunk

Reputation: 180

Like I said before: You re-define your count variable every time. So it will go back to 0 every time you click it. It will be best to define it outside the handle scope.

This should work (just define the count variable globally):

int count = 0;
button_help.setOnMousePressed(new EventHandler<MouseEvent>() {

    @Override
    public void handle(MouseEvent event) {
        count ++;

        System.out.println(count);
    }

});

Upvotes: 2

Klapsa2503
Klapsa2503

Reputation: 919

Your solution doesn´t work as you are reseting the value of variable every time you click button. You have to define it once and than just increase the valu of it.

Solution:

int count = 0;

button_help.setOnMousePressed(new EventHandler<MouseEvent>() {

    @Override
    public void handle(MouseEvent event) {
        count++;
        System.out.println(count);
    }

});

Upvotes: 3

Archival
Archival

Reputation: 21

You need to declare the int outside of the event handler or you just reset it each time the button is pressed.

Upvotes: 2

Related Questions