1

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);
    }


 });
user3770144
  • 105
  • 1
  • 2
  • 12
  • You re-define your count variable everytime. So it will go back to 0 everytime you click it. It will be best to define it outside the handle scope. – Frunk Oct 23 '14 at 09:00
  • But I do not mean to get count when the mouse is double or triple clicked. I want to get count when the button is just once pressed. – user3770144 Oct 23 '14 at 09:01
  • 2
    declare count globally instead of locally – Anik Islam Abhi Oct 23 '14 at 09:01
  • For checking if it is a double click, refer to the [link][1]. [1]: http://stackoverflow.com/questions/4051659/identifying-double-click-in-java – inf1ux Oct 23 '14 at 09:05
  • In your code int count = 0;declare in inside of event handler.so every time create new count count will print 1.declare count out side – Reegan Miranda Oct 23 '14 at 10:52

3 Answers3

3

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);
    }

});
Klapsa2503
  • 829
  • 10
  • 33
2

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

Archival
  • 21
  • 5
2

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);
    }

});
blalasaadri
  • 5,990
  • 5
  • 38
  • 58
Frunk
  • 180
  • 1
  • 2
  • 11