2017-02-24 78 views
-1
JLabel labels[][] = new JLabel[10][10]; //create a 10*10 matrix 
GameModel game=new GameModel(10); //10 is size 

    //this nested for is to check if numbers exist in matrix 
    for(int j = 0; j < game.getSize(); j++){ 
     for (int i =0; i < game.getSize(); i++){ 
      System.out.println(game.getDot()[j][i]); 
     } 
    } 

它正確打印,這是爲什麼一些點消失(標籤和圖像)

005 
011 
023 
035 
040 
052 
063 
072 
084 
092 
105 
113 
121 
133 
143 
152 
163 
174 
185 
193........., a total of 100 numbers(three numbers represent x-axis,y-axis,color respectively) 

//this nested for is to create labels and add picture to lables 
for(int j = 0; j < game.getSize(); j++){//getSize,which is 10 
     for (int i = 0; i < game.getSize(); i++) 
     { 
      labels[j][i] = new JLabel(); 
      P1.add(labels[j][i]); //JPanel p1; 

// getcolor(int x-axis,int y-axis)returns the color of a given dot, 
//which is the last number.for example,the color of "011" is 1, the color of "035" is 5  
      if(game.getColor(j,i)==0)//compare the last number 
       labels[j][i].setIcon(new ImageIcon("ball0.png")); 
      else if(game.getColor(j,i)==1) 
       labels[j][i].setIcon(new ImageIcon("ball1.png")); 
      else if(game.getColor(j,i)==2) 
       labels[j][i].setIcon(new ImageIcon("ball2.png")); 
      else if(game.getColor(j,i)==3) 
       labels[j][i].setIcon(new ImageIcon("ball3.png")); 
      else if(game.getColor(j,i)==4) 
       labels[j][i].setIcon(new ImageIcon("ball4.png")); 
      else if(game.getColor(j,i)==5) 
       labels[j][i].setIcon(new ImageIcon("ball5.png")); 
     } 
    } 
    f.add(P1);//JFrame f = new JFrame("hello"); 

但是當我運行它,它不給我正確的結果,一些點消失:

https://i.stack.imgur.com/0bieJ.png

+2

你在問爲什麼你的代碼無法正常工作,爲了回答這個問題,我們希望看到的不僅僅是代碼片段,還有不到整個代碼:a [mcve]。請閱讀該鏈接,然後考慮創建一個並在此處完全發佈您的問題。 –

+0

獲取圖像的一種方法(如@HovercraftFullOfEels所述)是熱鏈接到[本問答](http://stackoverflow.com/q/19209650/418556)中看到的圖像。 –

回答

1

並沒有真正回答你的問題(因爲我們沒有足夠的信息來解決你的問題),但這裏有一些調試/編碼提示:

  1. 你的循環,以檢查是否存在數量不證明一切。該循環使用getDot(...)方法。構建標籤的代碼使用getColor(...)方法。 getColor(...)方法可能無法達到您的預期。

  2. 不要創建100個圖標。圖標可以被標籤共享,所以你只需要創建6個圖標。然後你的循環中創建圖標的邏輯可以簡化。

  3. 變量名稱不應以大寫字符開頭。

所以你的代碼可能是這個樣子:

Icon[] icons = new Icon[6]; 
icons[0] = new ImageIcon("ball0.png"); 
icons[1] = new ImageIcon("ball1.png"); 
... 

for(int j = 0; j < game.getSize(); j++) 
{ 
    for (int i = 0; i < game.getSize(); i++) 
    { 
     // add your debug code here 

     int dot = game.getDot(...); 
     int color = game.getColor(...); 
     System.out.println(dot + " : " + color); 

     JLabel label = new JLabel(); 
     label.setIcon(icons[color]); 

     labels[j][i] = label; 
     p1.add(label); 
    } 
} 

現在您的調試代碼會告訴你,如果你當你真正創建標籤正確的價值觀,你會得到,如果一個錯誤顏色索引不是你所期望的。