开发者

Why isn't this int incrementing?

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;
       开发者_Go百科         positie = 0;
            }
        }
    });
}

Solved

Making the variable static solved my problem.

static int mijnScore = 0;


Please 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.


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 step


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)

// Score.java
public class Score {

    int mijnScore = 0;

    JLabel scoreSp1 = new JLabel();

    public Score(JDialog dialog) {
            dialog.add(scoreSp1);
    }

    ...

    public void updateUI() {
        // Code from question
    }
}

// Window.java
public class Game {

    ...

    public void scoredPoint() {
        JDialog dialog = new JDialog("You scored!");
        new Score(dialog).updateUI();
        dialog.setVisible(true);
    }
}

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:

// Window.java
public class Game {

    JDialog dialog = new JDialog("You scored!");

    Score score = new Score(dialog);

    ...

    public void scoredPoint() {
        score.updateUI();
        dialog.setVisible(true);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜