The count number of pressed button

你说的曾经没有我的故事 提交于 2020-01-06 03:51:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!