count button clicks

后端 未结 8 1903
天命终不由人
天命终不由人 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:29

    Depending on how you are instantiating this class you need to declare the clicked variable at either the field level or the class variable level. Currently, the scope of the clicked variable is local to the method.

    Option 1

    int clicked = 0;
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
     {                                         
      clicked++;
      System.out.println(clicked);
     }  
    

    Option 2

    static int clicked = 0;
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
     {                                         
      clicked++;
      System.out.println(clicked);
     } 
    

    The option you use will depend on instantiation. The second option should be avoided if possible.

提交回复
热议问题