将变量传递给事件调度线程
我的 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 传递给它而不将其声明为最终的(我不想这样做,因为它随着新玩家加入服务器而改变)
My GUI locks up because I need to update it through the EDT, however, I need to also pass a variable that is being updates with the GUI:
while ((message = this.in.readLine()).startsWith("NUMPLAYERS"))
{
numOfPlayers = Integer.parseInt(message.split(":")[1]);
numPlayers.setText("There are currently " + numOfPlayers + " players in this game");
}
This does not work. I need to set the text in the EDT but I cannot pass numOfPlayers to it without declaring it as final (which I don't want to do, because it changed as new players join the server)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的解决方案是使用
final
临时变量:The easiest solution would be to use a
final
temporary variable:您必须将其定为最终版本,或者让 Runnable 引用字段(类变量)。 如果引用一个字段,请确保它是线程安全的(通过同步或易失性)。
You have to make it final or have the
Runnable
reference a field (class varable). If referencing a field make sure that it's thread safe (via synchronized or volatile).怎么样:
注意:我认为OP有充分的理由不将
numOfPlayers
标记为final,也许稍后会在代码中的同一个while
循环中更改它与问题无关,因此未显示。 因此,numOfPlayers
是在while
循环之前声明的。如果没有这个假设,我就不会创建附加变量
newText
。How about this:
NOTE: I assume that the OP has a good reason for not marking
numOfPlayers
as final, perhaps that it is changed later in the samewhile
loop in code that's not relevant to the question, so not shown. And thus thatnumOfPlayers
is declared before thewhile
loop.Without this assumption, I wouldn't make the additional variable
newText
.在方法之外定义此类:(
出于本示例的目的,我假设有充分的理由说明为什么使用本地作用域的最终临时变量不起作用。老实说,我想不出该限制的任何原因,尽管。)
Define this class outside of your method:
(For the purposes of this example, I am assuming that there is a good reason why using a locally scoped final temp variable will not work. I honestly can't think of any reason for that restriction, though.)