Передающие переменные к Потоку Отправки События

$labelarray = array();
foreach ($valuearray as $value) 
{
   $labelarray[] = $value['label'];
}
print_r($labelarray);
5
задан Lii 13 January 2016 в 19:40
поделиться

4 ответа

Самое простое решение - использовать временную переменную final :

final int currentNumOfPlayers = numOfPlayers;
EventQueue.invokeLater(new Runnable() {
    public void run() {
       numPlayers.setText("There are currently " + 
               currentNumOfPlayers + " players in this game");
    }
});
10
ответ дан 18 December 2019 в 14:51
поделиться

Вы должны сделать его окончательным, иначе Runnable будет ссылаться на поле (переменная класса). Если вы ссылаетесь на поле, убедитесь, что оно потокобезопасное (через synchronized или volatile).

2
ответ дан 18 December 2019 в 14:51
поделиться

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.

1
ответ дан 18 December 2019 в 14:51
поделиться

Определите этот класс вне вашего метода:

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

(Для целей этого примера я предполагаю, что Это хорошая причина, по которой использование конечной временной переменной с локальной областью действия не будет работать. Однако я, честно говоря, не могу придумать причину такого ограничения.)

0
ответ дан 18 December 2019 в 14:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: