为什么这个 int 不递增?
我陷入了可能是一个简单的问题,但我真的找不到它不起作用的原因。我试图在每次调用该方法时将 mijnScore
增加 1。但不知何故,在该方法完成后,mijnScore
又回到了 0。
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;
}
}
});
}
已解决
使变量静态解决了我的问题。
static int mijnScore = 0;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅 SwingUtilities.invokeLater(..) 方法的 javadoc
http:// /download.oracle.com/javase/1.4.2/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)
可以执行 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.
我不知道您是否使用不同的对象或相同的对象进行调用。只是猜测将变量 mijnScore 设为静态然后可能就可以了。
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.
为什么你设置
ikWin = false;
然后循环在第一步结束why did you set
ikWin = false;
then loop ends in first step如果将其设为静态后它可以工作,那么您实际上可能会遇到不同的问题!
您是否在新构建的类上调用 updateUI() ?如果是这样,则仅在先前构造的实例上调用它,因为
mijnScore
是该实例的本地!编辑:
你们的课程是这样的吗? (也许您应该在问题中发布更多代码)
在这个愚蠢的示例中,问题实际上是在第二类中 - 您不应该每次都创建一个新的
Score
实例。例如,代码应该这样写: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: