如何在每次激活 JButton 时不重置 JLabel 中的值?

How to store the value in the JLabel without it resetting each time the JButton is activated?

我正在创建一个程序,当您输入大于 18 的值时,它会向 JLabel 添加 1,但是每次我单击该按钮时,程序都会重置回 1,而不是再添加一个。

例如,如果我输入另一个大于 18 的值,JLabel 应该再加一个,所以总数是两个...

这是我的代码:

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);    
}

您需要获取 JLabel 的当前值,然后将其加一。

jLabel3.setText(""+(Integer.parseInt(jLabel3.getText())+1));

目前,您的变量 totalOnetotalTwo 每次运行条件语句时都会重置为 0 值,因为它们是局部变量。