[英]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.