Search code examples
javaswingjbuttonjtextfield

How do I increase the number in the JTextField every time I press the JButton?


    private void vote1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    int vote1 = 0;
    int vote2 = 0;
    if (koonchk.isSelected()){
        vote1++;
    koontf.setText(Integer.toString(vote1));

    }
    else if (baamchk.isSelected()){
        vote2++;
    baamtf.setText(Integer.toString(vote2));

    }


}                                     

How do I increase the number in the JTextField every time I press the JButton?

how do I increase the number in the jtextfield every time I press the jbutton


Solution

  • You need to store int vote1 and vote2 outside of your method for vote1ActionPerformed, so that you dont reset the vote count to 0 every time.

    That way its really easy to update it to a bigger number each time. For example this would work:

    //Moved vote1/2 here outside of the method
    static int vote1 = 0;
    static int vote2 = 0;
    
        private void vote1ActionPerformed(java.awt.event.ActionEvent evt){                                      
            //We removed vote1 and vote2 from here and put them above
            if (koonchk.isSelected()){
            vote1++;
            koontf.setText(Integer.toString(vote1));
            }
            else if (baamchk.isSelected()){
            vote2++;
            baamtf.setText(Integer.toString(vote2));
            }
        }