Why isn't this int incrementing?

我的梦境 提交于 2019-12-08 06:45:10

问题


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;

回答1:


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.




回答2:


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.




回答3:


why did you set ikWin = false; then loop ends in first step




回答4:


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


来源:https://stackoverflow.com/questions/7753369/why-isnt-this-int-incrementing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!