java - 如何获取图像,然后使用它在 Java GUI 中制作 ImageIcon

标签 java arrays image user-interface

我正在尝试制作纸牌游戏,但我的 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();
  }

关于java - 如何获取图像,然后使用它在 Java GUI 中制作 ImageIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8303831/

相关文章:

javascript - 用于匹配字符串开头和结尾的两个单引号的正则表达式

php - 从 Android 上传图像到服务器不起作用

java - java中配置Logstash从socket接收数据并插入到Elasticsearch中

java - hadoop 映射器中的配置对象为空

javascript - 将用户推送到数组时,会创建多个数组

javascript - jQuery 比较数组并显示不匹配的值

java - 如何在Spring中临时授予用户角色?

java - Python:指定相同的通用参数类型

javascript - 在javascript中向图像添加标记?

java - 将graphics.Images转换为org.zkoss.image.Image