传递变量到事件分派线程
-
09-09-2019 - |
题
我的GUI锁,因为我需要通过EDT进行更新,但是,我还需要传递变量,其与所述GUI的更新:
while ((message = this.in.readLine()).startsWith("NUMPLAYERS"))
{
numOfPlayers = Integer.parseInt(message.split(":")[1]);
numPlayers.setText("There are currently " + numOfPlayers + " players in this game");
}
此不起作用。我需要设置在EDT的文字,但我无法通过numOfPlayers它没有宣布它作为最后的(我不想这样做,因为它改变了作为新玩家加入服务器)
解决方案
的最简单的解决办法是使用一个final
临时变量:
final int currentNumOfPlayers = numOfPlayers;
EventQueue.invokeLater(new Runnable() {
public void run() {
numPlayers.setText("There are currently " +
currentNumOfPlayers + " players in this game");
}
});
其他提示
您必须使它最终或具有Runnable
参考的字段(类varable)。如果引用一个字段确保它是线程安全的(通过同步或挥发性的)。
这样如何:
while ((message = this.in.readLine()).startsWith("NUMPLAYERS")) {
numOfPlayers = Integer.parseInt(message.split(":")[1]);
final newText = "There are currently " + numOfPlayers + " players in this game";
EventQueue.invokeLater(new Runnable() {
public void run() {
numPlayers.setText(newText);
}
});
}
请注意:我假设OP有一个很好的理由不标记numOfPlayers
作为最终,或许它是在代码相同的while
循环,是不相关的问题,后来改变,因此未显示。并且因此numOfPlayers
在while
循环之前声明。
如果没有这个假设,我不会使另外的可变newText
。
定义的方法以外此类:
public abstract class MyRunnable implements Runnable {
protected int var;
public MyRunnable (int var) {
this.var = var;
}
}
Now your code can look like this:
SwingUtilities.invokeAndWait(new MyRunnable(5) {
@Override
public void run() {
//numPlayers.setText("There are currently " + var + " players in this game");
}
});
(在这个例子的目的,我假设有就是为什么使用本地范围的最终温度变量是行不通的一个很好的理由。老实说,我想不出任何理由这个限制,虽然)。
不隶属于 StackOverflow