2013-05-15 94 views
0

我有一個JFrame「GameWindow」和一個名爲「Combat」的類。JFrame中的更新信息

我想從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); 

爲什麼針對按鈕/的JLabel文本沒有更新?我是否需要將「Combat.variable」改爲「Combat.getVariable()」?這甚至是可能的,如果是這樣,我該如何使它工作?

+1

*什麼*不起作用?我的MouseListener中根本沒有看到任何代碼,所以一定不會做任何事情。順便提一句,不要在JButton中使用MouseListener。使用ActionListener作爲教程,我相信你會閱讀這些教程。如果您仍然需要幫助,請考慮創建併發佈一個非常小的簡單程序,它可以編譯,運行,向我們顯示您的問題,並且只會執行此操作,而不會再執行[sscce](http://sscce.org)。 –

+0

「我試圖從Combat類的變量中更新GameWindow(JLabels,JProgressBars等)中的各種組件,爲什麼這不起作用? – Aaron

+0

上面的代碼在哪裏顯示我們嘗試執行此操作的位置?你的代碼中有什麼不起作用?再次,擺脫MouseListener併爲JButton使用ActionListener。 –

回答

2

幽州:

JButton的pAttack1 =的新的JButton(Combat.attackName1);如上所述,在更改戰鬥類中的變量時,JButton上的文本不會更新。

您將引用變量與它所表示的對象相混淆,並且需要明白它們是不同的。雖然最初Combat.attackName1和JButton的名稱引用同一個String對象,但Strings是不可變的。當您更改變量所指的字符串對象時,這將不會影響JButton顯示的字符串。解決方案:如果要更改其顯示的文本,請調用JButton的setText(...)方法。