簡體   English   中英

如何獲取圖像,然后使用它在Java GUI中制作ImageIcon

[英]How can I get an Image and then Use it to make an ImageIcon in Java GUI

我正在嘗試制作紙牌游戲,而我的getImage()函數遇到問題。 我有一個紙牌的字符串數組,例如:

private static String[] hearts = {"ah.gif","2h.gif","3h.gif","4h.gif","5h.gif","6h.gif","7h.gif","8h.gif","9h.gif","th.gif","jh.gif","qh.gif","kh.gif"};

我的getImage()看起來像這樣:

public String getImage(Card card){

    if (0 == suit){
        img = hearts[rank];
    }
    else if (1 == suit){
        img = spades[rank];
    }
    else if (2 == suit){
        img = diamond[rank];
    }
    else if (3 == suit){
        img = clubs[rank];
    }

但是,因為它存儲為字符串,所以當我嘗試將img用作ImgIcon Ex時出現錯誤:

    ImageIcon image = (card.getImage(card));
    JLabel label = new JLabel(image);

有任何想法嗎? 謝謝

創建一個ImageIcons數組,並使用String數組和一個for循環創建Icon數組。 簡單。 :)

// in declaration section  
private ImageIcon heartsIcons = new ImageIcon[hearts.length];  

  // in code section
  try {
     for (int i = 0; i < hearts.length; i++) {
        // you may need different code to get the Image file vs. resource.
        BufferedImage img = ImageIO.read(getClass().getResource(hearts[i]));
        heartsIcons[i] = new ImageIcon(img);
     }
  } catch (IOException e) {
     e.printStackTrace();
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM