gpt4 book ai didi

java - JFrame 中的更新信息

转载 作者:行者123 更新时间:2023-12-02 07:01:51 24 4
gpt4 key购买 nike

我有一个 JFrame“GameWindow”和一个名为“Combat”的类。

我正在尝试从 Combat 类中的变量更新 GameWindow 中的各种组件(JLabels、JProgressBars 等)。然而,细节似乎从未更新。考虑以下因素:

public class Combat {
public static String attackName1;
public static String pUnitName;

public static void setPlayerUnit(GameUnit u) {

attackName1 = u.getAttackName1();
pUnitName = u.getName().toUpperCase();
}
}

和:

 public GameWindow() {

initialize();
gameFrame.setVisible(true);
}

private void initialize() {
gameFrame = new JFrame();
gameFrame.setResizable(false);
gameFrame.setTitle("GameWindow");
gameFrame.setBounds(100, 100, 800, 480);
gameFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

JButton pAttack1 = new JButton(Combat.attackName1); //<--------NOT BEING CHANGED
sl_gamePanel.putConstraint(SpringLayout.NORTH, pAttack1, 0, SpringLayout.NORTH, gameTextPanel);
sl_gamePanel.putConstraint(SpringLayout.WEST, pAttack1, 6, SpringLayout.EAST, textAttackSeparator);
sl_gamePanel.putConstraint(SpringLayout.SOUTH, pAttack1, 34, SpringLayout.NORTH, gameTextPanel);
sl_gamePanel.putConstraint(SpringLayout.EAST, pAttack1, 157, SpringLayout.EAST, textAttackSeparator);
gamePanel.add(pAttack1);

JLabel pMobName = new JLabel(Combat.pUnitName); //<--------NOT BEING CHANGED
sl_pPanel.putConstraint(SpringLayout.NORTH, pMobName, 10, SpringLayout.NORTH, pPanel);
sl_pPanel.putConstraint(SpringLayout.WEST, pMobName, 129, SpringLayout.WEST, pPanel);
pPanel.add(pMobName);

为什么按钮/JLabels 的文本没有更新?我需要将使用“Combat.variable”更改为“Combat.getVariable()”吗?这是否可能,如果可以,我怎样才能让它发挥作用?

最佳答案

您声明:

JButton pAttack1 = new JButton(Combat.attackName1); As stated, the text on the JButton is not updated when changing the variable in the combat class.

您将引用变量与其表示的对象混淆了,需要了解它们是不同的。虽然最初 Combat.attackName1 和 JButton 的名称引用同一个 String 对象,但字符串是不可变的。当您更改变量引用的 String 对象时,这不会对 JButton 显示的 String 产生影响。解决方案:如果要更改其显示的文本,请调用 JButton 的 setText(...) 方法。

关于java - JFrame 中的更新信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16555938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com