2013-01-19 30 views
2

我正在編碼圖像益智遊戲,代碼的一部分是比較用戶選擇的部分片段的正確圖像。JButton的隱藏setText值

每個圖像片段已作爲ImageIcon添加到JButton中。

需要一個標識符來區分每個圖像塊並進行比較。

我正在爲每個JButton創建一個setText()作爲標識符。

但這樣做會導致ImageIcon和setText在JButton上顯示。

有沒有辦法隱藏setText的值,只顯示ImageIcon?

 private String id; 
     private int cc; 
     private JButton[] button = new JButton[9]; 

     cc += 1; 
     id += ""+cc; 

     for(int a=0; a<9; a++){ 
      // dd refers to the variable for the image pieces for each JButton 
     button[a].setIcon(new ImageIcon(dd)); 
     button[a].setText(id); 
     } 
+1

可以使用_Map_用於存儲每個ID爲每個按鈕。所以你可以用這個_Map_標識每個按鈕。或者,您可以爲每個按鈕和每個圖像使用_setName_。 – Amarnath

+1

恕我直言,代替比較'JButton'的'圖像',你可以使用一個與'JButton'數組大小相同的int數組,並且只需將一個數字與每個'ImageIcon'相關聯,因此你可以比較這個數組值以獲得您想要的結果。或者,您可以使用[setName()]而不是使用'setText()'(http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#setName(java.lang。字符串)),作爲此方法的替代方法。 –

+1

2個有趣的方法,'Map'和'setName()'。將閱讀他們:) – iridescent

回答

2

我建議製作String是另一個數組:

String[] ids = new String[button.length]; 

然後button[a]的ID將是ids[a]

這裏是你的代碼的變化:

private String id; 
    private int cc; 
    private JButton[] button = new JButton[9]; 
    private String[] ids = new String[button.length]; 

    //cc += 1; 
    //id += ""+cc; 
    id += Integer.toString(++cc); //easier way 

    for(int a=0; a<9; a++){ 
     // dd refers to the variable for the image pieces for each JButton 
     button[a].setIcon(new ImageIcon(dd)); 
     ids[a] = id; 
    } 
+0

是的,我也得到了這一點,這就是爲什麼我的評論是消失了1的想法,由你提供:-)儘管我仍然認爲你錯過了在修改後的代碼中添加你提出的建議。 –