【问题标题】:How to add an image to an object in Java? [duplicate]如何将图像添加到 Java 中的对象? [复制]
【发布时间】:2015-04-10 05:33:37
【问题描述】:

我正在尝试为每个卡片对象添加正确的图像,但我似乎无法让它工作。我试图将它合并到我的 fillDeck() 方法中,但不确定最好的方法是什么。

这是我得到的:

public void fillDeck() {
    Iterator suitIterator = CardSuit.VALUES.iterator();
    while(suitIterator.hasNext()) {
        CardSuit suit = (CardSuit) suitIterator.next();
        Iterator rankIterator = CardValue.VALUES.iterator();

    while(rankIterator.hasNext()) {
        CardValue value = (CardValue) rankIterator.next();  

        /* This is the problem area :L */
        String imageFile = imageLocation + Card.getImageFilename(suit, value);
        ImageIcon image = new ImageIcon(getImage(getCodeBase(), imageFile));
       /* --------------------------- */

        Card card = new Card(suit, value, image);
        addCard(card);
    }}}

图片位置初始化为:private final String imageLocation = "cardImages/";

而getImageFilename如下:

public static String getImageFilename( CardSuit suit, CardValue value ) {
    return suit.getSuitAcronym() + value.getValueAcronym() + ".png";
}

我正在检查 imageIO,但不太确定如何将其实现到其中。这也是我的文件树,可能是我将图像文件夹放在错误的位置:http://i.stack.imgur.com/Jt6po.png

所以,是的,很抱歉这篇长文,希望有人能提供一些关于我应该如何处理这个问题的见解,或者你是否能发现一些错误。

【问题讨论】:

    标签: java image


    【解决方案1】:

    在 Java 中加载图像:

    BufferedImage image = null;
    
    try{
        image = ImageIO.read(new File("location.png"));
    } catch(Exception e){e.printStackTrace();}
    

    【讨论】:

    • 现在它至少填满了卡片组,但找不到图像。它给出了 javax.imageio.IIOException: Can't read input file!这是否意味着图像路径错误还是其他原因?
    • while(rankIterator.hasNext()) { CardValue value = (CardValue) rankIterator.next(); String imageFile = imageLocation + Card.getImageFilename(suit, value); try { testImage = ImageIO.read(new File(imageFile)); } catch(Exception e) { e.printStackTrace(); } Card card = new Card(suit, value, testImage); addCard(card); }
    • @FroZenL1Qu1d 您无法在 cmets 中格式化代码。如果您需要代码,请考虑编辑您的问题。
    • 好吧,不知道要在问题中编辑什么,我只是无法让它为我的生活工作。那个“重复”的问题没有用,谷歌搜索了 4 个多小时后,仍然没有。
    猜你喜欢
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2021-03-22
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多