2014-05-13 73 views
0

我有一個JLabel PlayerLabel陣列PlayerName數組,它是intialised以下方式字符串變量突然變得字母的組合和數量

 String [] PlayerName; 
     PlayerName = new String[4]; 
     for (int i=0;i<4;i++) 
     { 
      PlayerName[i] = "None1"; 

     } 

JLabel [] PlayerLabel; 

PlayerLabel = new JLabel[4]; 

     for (int i=0;i<4;i++) 
     { 
      String num = Integer.toString(i); 
      String output = "Player " + num + " : " + PlayerName; 

      PlayerLabel[i] = new JLabel(output); 
      PlayerLabel[i].setForeground(Color.white); 

     } 

我希望我的JLabel到文本是

玩家1:None1

相反,我得到

玩家1:java.lang.String中; @ 4e9fd887

@15150ef8部分更改數字和字母的不同組合,每次我重新啓動程序。

PlayerName是好的,當我初始化它 enter image description here

我不知道爲什麼,當它在輸出

enter image description here

什麼是添加的PlayerName變得怪異發生,我該如何解決這個問題?

回答

10

當你做+ Playername,你打印陣列本身,而不是數組中的元素。當您嘗試來連接對象爲一個字符串,該對象的toString()方法被調用和數組繼承toString()Object

public String toString() { 
    return getClass().getName() + "@" + Integer.toHexString(hashCode()); 
} 

而這可能不是你想要的。您可能想要做Playername[i]

0

這將打印數組的某一元素在你的字符串的結尾:

String output = "Player " + num + " : " + PlayerName[i];