count button clicks

后端 未结 8 1893
天命终不由人
天命终不由人 2020-12-16 08:58

I want to count the number of times the button is clicked using GUI.

I did this code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent         


        
相关标签:
8条回答
  • 2020-12-16 09:10

    You've declared clicked as a local variable, initialised to 0, it can never be anything else but 1

    Make clicked a class level variable instead...

    private int clicked = 0;
    
    //...
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
    {                                         
        clicked++;
        System.out.println(clicked);
    } 
    
    0 讨论(0)
  • 2020-12-16 09:15

    You are resetting the counter every time you click, because you have defined the variable inside the action method. Try not doing that.

    int clicked = 0; // move this outside
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
    {                                         
        // int clicked = 0; -- this resets it to 0 each time
        clicked++;
        System.out.println(clicked);
    }
    
    0 讨论(0)
  • 2020-12-16 09:18

    You have declared count variable inside the ActionListener. Declare it outside the block.

    int clicked = 0;  //make it as your class member.
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
    {                                         
    
      clicked++;
      System.out.println(clicked);
    }    
    
    0 讨论(0)
  • 2020-12-16 09:18

    every time jButton1ActionPerformed fires, the clicked variables gets instantiated back to 0 that's why it is always giving you a value of 1. You should move the clicked variable outside of that method

    //Somewhere in your class
    private intClicked = 0;
    //More methods here.
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
     {                                         
      clicked++;
      System.out.println(clicked);
     }
    
    0 讨论(0)
  • 2020-12-16 09:21

    Try below code

    int clicked = 0;
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
     {                                         
    
      clicked++;
      System.out.println(clicked);
     } 
    
    0 讨论(0)
  • 2020-12-16 09:26

    Change

    int clicked = 0;
    

    to be a member of your class. This way it wont be set to zero every time you press the button.

    0 讨论(0)
提交回复
热议问题