绘制JLabel时,我的JLabel以变量0开始。另一个线程不断增加此值,我想更新标签。
如果可能的话,我不希望线程访问标签。 (gm.getPlayerByListIndex(index).getAlk())得到更新
[
{
"clusters": [
{
"sentences": [
" Qoum & Maa Baap K Duaon Se Award Haasil Kiya",
" Qoum & Maa Baap K Duaon Se Award Haasil Kiya",
" Qoum & Maa Baap K Duaon Se Award Haasil Kiya"
],
"summary": " Qoum & Maa Baap K Duaon Se Award Haasil Kiya. Qoum & Maa Baap K Duaon Se Award Haasil Kiya."
},
{
"sentences": [
" Mushtaq Ahmed",
" Mushtaq Ahmed",
" Mushtaq Ahmed NIJAMHAMY"
],
"summary": " Mushtaq Ahmed. Mushtaq Ahmed NIJAMHAMY."
}
]
}
]
增加价值的线程:
createPlayer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean checked = checkInputs(nameInput, difficultyInput);
if (checked) {
String playername = getInput(nameInput);
addPlayerToMainWindow(gm.getRegisteredPlayers().size(), playername);
gm.createPlayer(playername, Integer.parseInt(getInput(difficultyInput)));
dialog.dispose();
JLabel alkLabel = new JLabel(Integer.toString(gm.getPlayerByListIndex(index).getAlk()));
window.getWindow().getContentPane().add(alkLabel);
alkLabel.setVisible(true);
alkLabel.setBounds(160, (120 * index) + 50, 100, 50);
}
}
});
答案 0 :(得分:0)
在这种情况下,您可以使用Observer pattern。
您将需要和Observer这样的类(注意:),该实现假定library(tidyverse)
df %>%
mutate_all(str_remove, "0+$") %>%
map2_dfr(., df, ~
tibble(x = nchar(.x), grp = nchar(.y)) %>%
group_by(grp) %>%
summarise(x = median(x)), .id = 'colName')
# A tibble: 7 x 3
# colName grp x
# <chr> <int> <dbl>
#1 A 3 3
#2 A 4 4
#3 A 5 5
#4 B 1 1
#5 B 2 2
#6 C 2 2
#7 C 3 2.5
和equals
在hashCode
类中实现):
Player
现在您的分配器类应该充当Obervable类,因此您的public class JLabelObserver{
private JLabel label;
private Player player;
public JLabelObserver(JLabel label, Player player){
this.label = label;
this.player = player;
}
public update(Player player){
if(this.player.equals(player))
label.setText(player.getAlk())
}
}
看起来像这样:
Dispenser
最后,在创建JLabel之后,还创建并观察者:
public class Dispenser extends Thread {
List<Player> players = GameManager.getInstance().getRegisteredPlayers();
List<JLabelObserver> observers = new ArrayList<>();
public void run() {
while (true) {
System.out.println("alive");
try {
for (Player p : players) {
p.setAlk(p.getAlk() + p.getDifficulty()); // TODO too hard
notifyObservers(p)
}
} catch (ConcurrentModificationException e) {
System.out.println("playerlist in use, retry");
}
try {
sleep(1000); // TODO too short
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public static addObserver(JLabelObserver observer){
observers.add(observer);
}
public static notifyObservers(Player player){
for(JLabelObserver observer : observers){
observer.update(player);
}
}
}