Reputation: 3
I'm creating a program that when you enter a value greater than 18 it adds one to the JLabel
however each time I click the button the program resets back to 1 instead of adding an additional one.
For example if I enter another value greater than 18, the JLabel
should add an additional one so the total is two...
This is my code:
int age = Integer.parseInt(jTextField1.getText()); // gets the value from the button click
if(age >= 18){ // determines if it is greater then 18
int totalOne = 0;
totalOne = totalOne + 1;
String totalAgeOne = Integer.toString(totalOne);
jLabel3.setText(totalAgeOne); // sets the jlabel to One
}else{
int totalTwo = 0;
totalTwo = totalTwo + 1;
String totalAgeTwo = Integer.toString(totalTwo);
jLabel5.setText(totalAgeTwo);
}
Upvotes: 0
Views: 66
Reputation: 609
You need to get the current value of the JLabel, and then add one to it.
jLabel3.setText(""+(Integer.parseInt(jLabel3.getText())+1));
Currently, your variable totalOne
and totalTwo
reset to the value of 0 ever time it runs through the conditional statement because they are local variables.
Upvotes: 1