Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 916
Logan Serman Avatar asked Apr 15 '09 21:04

Logan Serman


3 Answers

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");
    }
});
like image 56
Michael Myers Avatar answered Oct 19 '22 07:10

Michael Myers


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).

like image 2
Steve Kuo Avatar answered Oct 19 '22 05:10

Steve Kuo


How about this:

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);
        }
    });
}

NOTE: I assume that the OP has a good reason for not marking numOfPlayers as final, perhaps that it is changed later in the same while loop in code that's not relevant to the question, so not shown. And thus that numOfPlayers is declared before the while loop.

Without this assumption, I wouldn't make the additional variable newText.

like image 1
Eddie Avatar answered Oct 19 '22 06:10

Eddie