Search code examples
javamultithreadingevent-dispatch-thread

Passing variables to the Event Dispatch Thread


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)


Solution

  • The easiest solution would be to use a final temporary variable:

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