ugCode
ugCode

Reputation: 29

Counter variable for actionevent

I have an int variable that is set a certain value, when a JButton is clicked on the GUI the buttons visibility is set to false, and the counter variable should decrease by one. Once it hits 0 an if statement is executed. The problem is the counter variable keeps getting reset everytime I click a button. This is my code

public int someMethod(){
    intVar= 3;
    return intVar;
}

public void anotherMethod(){
    intVar--;
}
public void actionPerformed(ActionEvent e) {
if (someCondition){
            clickedButton.setVisible(false);
            anotherMethod();
            if (someMethod()==0){
  //Do something
  }

Upvotes: 0

Views: 88

Answers (2)

Mshnik
Mshnik

Reputation: 7032

Your someMethod() resets the counter to 3. Thus it will always return 3. Thus your if block will never be executed.

someMethod() is logically equivalent to the following, barring any concurrency shenanigans:

public int someMethod() {
    intVar = 3;
    return 3;
}

Thus your actionPerformed(...) is logically equivalent to the following (ibid):

public void actionPerformed(ActionEvent e) {
    if (someCondition){
        clickedButton.setVisible(false);
        anotherMethod();
        if (3==0){
            //Do something
        }
    }
}

If the counter should just decrease, and the if block should be executed when intVar == 0 just use the intVar directly in your comparison:

public int anotherMethod(){
    return --intVar;
}

public void actionPerformed(ActionEvent e) {
    if (someCondition){
        clickedButton.setVisible(false);
        anotherMethod();
        if (intVar==0){
            //Do something
        }
    }
}

Or, remove the assignment from someMethod():

public int someMethod() {
    return intVar;
}

Or, get rid of someMethod() call here and return the updated counter value from 'anotherMethod()' to change code to:

public int anotherMethod(){
    return intVar--;
}

public void actionPerformed(ActionEvent e) {
    if (someCondition){
        clickedButton.setVisible(false);
        if (anotherMethod()==0){
            //Do something
        }
    }
}

Upvotes: 3

Aaditya Gavandalkar
Aaditya Gavandalkar

Reputation: 824

Its because in method someMethod() you always end up resetting the variable to 3. Instantiate the variable outside the method only once.

Another interesting fact (not related to this), Integers from -127 to +128 are stored in the integer pool (cached) and any reference to value in the range is done to object in pool. (Applicable for Integer only and not ints)

Upvotes: 1

Related Questions