2009-04-15 25 views
5

我的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傳遞給它,但不聲明它是最終的(我不想這麼做,因爲它隨着新玩家加入服務器而改變)

回答

10

最簡單的解決方案是使用final臨時變量:

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

在這種情況下,它只需要在適當的點(最終)定義局部變量。 – 2009-04-15 22:26:09

2

你必須使它最終還是有Runnable參考字段(類varable)。如果引用一個字段,確保它是線程安全的(通過synchronized或volatile)。

+0

我將如何引用類變量?這將是理想的。 – 2009-04-16 02:24:33

1

如何:

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循環中的代碼改變這是不相關的這個問題,所以沒有顯示。因此numOfPlayerswhile循環之前被聲明。

沒有這個假設,我不會做額外的變量newText

+0

在大寫的新文本之前缺少字符串。將聲明放在正確的位置後,可能會使numOfPlayers本身最終生效。 – 2009-04-15 23:46:23

0

定義這個類的方法之外:

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

(在這個例子的目的,我假設有就是爲什麼使用本地範圍的最終溫度變量是行不通的一個很好的理由說實話。儘管如此,我們不能想到這種限制的任何原因。)