2012-05-17 65 views
0

對於學校我需要製作一張處理[X]隨機卡片的遊戲。 我使用此代碼來建立和顯示我的圖像。 只有一件事出錯了。顯示項目時,僅顯示最後一張牌 。如何在for循環中顯示多張圖片

有什麼辦法可以將這些圖像放在一起?

public static void main(String[] args) throws FileNotFoundException, IOException { 
    Cards cards = new Cards(); 
    int dealSize = 6; 
    deal = cards.getShuffledCards(dealSize); 
    System.out.println("Deal of 4 randomly picked cards " + deal); 
    f = new JFrame(); 
    for(int i=0; i < dealSize; i++) { 
     card = deal.get(i).toString(); 
     f.getContentPane().add(setLabel(card)); 
    } 
    f.pack(); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.setLocation(200,200); 
    f.setVisible(true); 



} 

public static JLabel setLabel(String fileLocation) throws FileNotFoundException, IOException { 
    InputStream file = new BufferedInputStream(
     new FileInputStream([DIRECTORY TO IMAGES]" + fileLocation)); 
     BufferedImage image = ImageIO.read(file); 
     label = new JLabel(new ImageIcon(image)); 
     return label; 

} 

回答

2

您可能必須製作一張任意網格,其中一張卡片可以佔據每個部分。像GridLayout或GridBagLayout一樣。

通過瀏覽你的代碼,你基本上覆蓋了你放置的最後一個元素,每次迭代。

+0

這就是我也害怕的。但我真的不知道如何能夠動態地添加圖像 – Arthur

+0

正如我所說,嘗試不同的佈局。像GridLayout一樣。如果你被允許,你可以很容易地在像NetBeans這樣的GUI構建器中進行設置。 – OmniOwl