我无法用新数据更新 JPanel。我正在开发一款游戏,我正在尝试做的基本概念是加载玩家并在 JPanel 中显示他持有的项目(以框布局设置)我正在使用线程和循环来更新播放器物品。这对一个玩家来说效果很好,但我的游戏允许用户可以在其他玩家之间切换。当我切换到下一个播放器时,我希望加载和更新他们的详细信息。这行不通。
这只是代码片段,但我希望有人能够看到我的问题。
private JFrame frame;
private JPanel mainPanel;
private Box Item1 Item2, Item3;
static private JPanel centerPanel;
private boolean playerLoaded;
private Player currentPlayer;
private Thread gameThread;
public void run(){
while (running){
for (Player player:allPlayers){
playerLoaded = false;
currentPlayer = player;
player.setCurrentTurn(true);
while (player.isCurrentTurn()){
if (playerLoaded != true){
loadPlayer(player);
loadItems(player);
playerLoaded = true;
}
if ((playerLoaded == true){
updateItems(player);
try {
Thread.sleep(999);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public void loadPlayer(Player player){
jlCurrentPlayer.setText("Player: " + player.getName());
}
public void loadItems(Player player){
int count = 1;
centerPanel = new JPanel(new GridLayout(1,3));
for (Item Item : player.getAllItems()){
if (count == 1) {
Item1 = Box.createVerticalBox();
Item1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel jlItem = new JLabel(item.getName());
Item1.add(jlItem);
centerPanel.add(Item1);
}
else if (count ==2){
Item2 = Box.createVerticalBox();
Item2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel jlItem = new JLabel(item.getName());
Item2.add(jlItem);
centerPanel.add(Item2);
}
else if (count ==3){
Item3 = Box.createVerticalBox();
Item3.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel jlItem = new JLabel(item.getName());
Item3.add(jlItem);
centerPanel.add(Item3);
}
mainPanel.add(centerPanel,BorderLayout.CENTER);
count++;
}
}
public void updateItemstats(Player player){
int count = 1;
if (player.isCurrentTurn()){
for (Item item : player.getAllItems()){
if ((count == 1) && (player.isCurrentTurn())) {
Item1.add(Box.createVerticalGlue());
Item1.add(new JLabel("Value: " + item.getstats().getValue()));
Item1.add(new JLabel("Quality: " + item.getStats().getQuality()));
}
else if (count ==2){
Item2.add(Box.createVerticalGlue());
Item2.add(new JLabel("Value: " + item.getstats().getValue()));
Item2.add(new JLabel("Quality: " + item.getStats().getQuality()));
}
else if (count ==3){
Item3.add(Box.createVerticalGlue());
Item3.add(new JLabel("Value: " + item.getstats().getValue()));
Item3.add(new JLabel("Quality: " + item.getStats().getQuality()));
}
count++;
}
}
}
JButton jbNext = new JButton("Next Player");
jbNext.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentPlayer.setCurrentTurn(false);
}
});
对于我的主框架,我使用的是边框布局。当我切换播放器时发生的情况基本上是更新的信息有时是播放器 1 和 2 的混合。例如
价值 25 质量 60
值 50 质量 20。
此外,如果玩家 1 有 1 个物品,玩家 2 有 3 个物品,而我从玩家 2 切换到 1,有时玩家 1 将拥有玩家 2 的所有物品,而不是他自己的。
我认为这可能是 Item1 2 和 3 面板的问题,所以我尝试在下一个玩家 btn 点击时将它们删除,但这只是导致了异常。这很可能仍然是问题,我可能没有正确删除它们。
有人可以帮我解决这个问题吗?