将变量传递给Event Dispatch Thread

Log*_*man 5 java multithreading event-dispatch-thread

我的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");
}
Run Code Online (Sandbox Code Playgroud)

这不起作用.我需要在EDT中设置文本,但我不能将numOfPlayers传递给它而不将其声明为final(我不想这样做,因为它随着新玩家加入服务器而改变)

Mic*_*ers 10

最简单的解决方案是使用final临时变量:

final int currentNumOfPlayers = numOfPlayers;
EventQueue.invokeLater(new Runnable() {
    public void run() {
       numPlayers.setText("There are currently " + 
               currentNumOfPlayers + " players in this game");
    }
});
Run Code Online (Sandbox Code Playgroud)