I am stuck on probably an easy problem, but I really can't find why it isn't working. I am trying to increase mijnScore
with 1 each time the method gets called. But somehow mijnScore
goes back to 0 after the method is done.
int mijnScore = 0;
...
public void updateUI() {
System.out.println("updateUI");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ikWin = true;
while(ikWin) {
mijnScore++;
System.out.println("mijnScore" + mijnScore);
Scoresp1.setText(mijnScore + "");
ikWin = false;
positie = 0;
}
}
});
}
Solved
Making the variable static solved my problem.
static int mijnScore = 0;
If it works after you made it static, you might actually have a different problem!
Do you call updateUI() on a newly constructed class? If so, only call it on a previously constructed instance as
mijnScore
is local to that instance!EDIT:
Do your classes look like this? (Maybe you should have posted more code in the question)
In this silly example, the problem is actually in the second class - you shouldn't create a new
Score
instance every time. For the example, the code should be written like this:I dont know wheather you are calling with different objects or same.Just as a guess Make the variable mijnScore static then it may be ok.
why did you set
ikWin = false;
then loop ends in first stepPlease see the javadoc of the method SwingUtilities.invokeLater(..) http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)
It can be that the thread doing the mijnScore increments is invoked only later and this is why in the parent thread you see still the value 0 for it.