问题
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);
}
});
回答1:
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);
}
});
回答2:
You need to declare the int outside of the event handler or you just reset it each time the button is pressed.
回答3:
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);
}
});
来源:https://stackoverflow.com/questions/26524583/the-count-number-of-pressed-button