处理图像文件的java程序的空指针异常

时间:2013-11-19 01:52:46

标签: java nullpointerexception

所以我有一个应该显示卡片图像文件的程序。 (这是另一个进行战争卡片游戏的程序。)

然而,当我运行它时,我收到此错误:

Error opening file.
The first node is: Node [suit=3, card =2, next=null]
Exception in thread "main" java.lang.NullPointerException
    at Card.getImage(Card.java:118)
    at Card.main(Card.java:187)

我做错了什么?我有一个完全相同代码的合作伙伴,但他的工作正常。我们都在Eclipse中编码。

我的代码:

public class Card {

    //// card definitions ////
    public static final int DUMMY = 9999999;    // a constant indicating a dummy node
    public static final int CLUB = 0;       // clubs
    public static final int SPADE = 1;      // spades
    public static final int HEART = 2;      // hearts
    public static final int DIAMOND = 3;    // diamonds
    public static final String IMAGEFILENAME = "classic-playing-cards.png"; // image file
    public static final int CARDWIDTH = 73; // card width
    public static final int CARDHEIGHT = 98;    // card height

    //// class member ////
    private static BufferedImage img = null;

    //// data members ////
    private int suit;           // the suit  
    private int value;          // the card value, 0=ace, 1=deuce, 2=3 ... 10=9, Jack=10, Queen=11, King=12
    private JLabel image;       // the card image file
    private Card next;          // a link to the next node

    //// Constructors ////
    public Card() {
        // initialize to be a dummy node by default
        suit = DUMMY;
        value = DUMMY;
        image = null;
        next = null;

        // check to see if the buffered image is loaded
        if (img == null) {
            // not yet loaded, so load it now!
            loadBufferedImage();
        }
    }


   public String getSuitName() {
      if (suit == CLUB) 
         return "Club";
      else
      if(suit == SPADE)
         return "Spade";
      else
      if(suit == HEART)
         return "Heart";
      else
      if(suit == DIAMOND)
         return "Diamond";
      else
         return "Invalid suit number.";
      }


    //// Set up the buffered image
    public void loadBufferedImage() {
        try {
            // get the path to the image file name
            java.net.URL imgURL = getClass().getResource(IMAGEFILENAME);
            if (imgURL != null) {
                // read the image file, using the path
                img = ImageIO.read(new File(imgURL.getFile()));
            } else {
                System.out.println("Couldn't find file: " + IMAGEFILENAME);
            }
        } catch (Exception e) {
            System.out.println("Error opening file.");
            image = new JLabel("Error");
        }
    }

    /**
     * @return the suit
     */
    public int getSuit() {//suit getter
        return suit;
    }

    /**
     * @return the card
     */
    public int getCard() {//card getter
        return value;
    }

    /**
     * @return the card's image
     */
    public JLabel getImage() {
        // as long as it's not a dummy card
        if (value != DUMMY && suit != DUMMY) {
            // create a JLabel for display, for just the card that we want
            image = new JLabel(new ImageIcon(img.getSubimage(CARDWIDTH*value,CARDHEIGHT*suit,CARDWIDTH,CARDHEIGHT)));
        } else {
            // oops, error!  just display the text "DUMMY"
            image = new JLabel("DUMMY");
        }
        return image;
    }

    /**
     * @return the next
     */
    public Card getNext() {
        return next;
    }

    /**
     * @param suit the suit to set
     */
    public void setSuit(int suit) {
        this.suit = suit;
    }

    /**
     * @param card the card to set
     */
    public void setCard(int card) {
        this.value = card;
    }

    /**
     * @param next the next to set
     */
    public void setNext(Card next) {
        this.next = next;
    }

    //// deepCopy ////
    /* create a duplicate copy of this node */
    public Card deepCopy() {
        Card copy = new Card();  // the duplicate node

        // fill contents
        copy.setSuit(suit);  // duplicate the data
        copy.setCard(value);
        // do not need to set the image, since we recalculate it each time
        copy.setNext(null);  // set next to be a null pointer, this node is not in a list

        // return the copy
        return copy;
    }

    //// Auto generate toString() using Eclipse ////
    public String toString() {
        return "Node [suit=" + suit + ", card =" + value + ", next=" + next + "]";
    }

    //// main() for testing ////
    public static void main(String[] args) {

        // create a card:  the 3 of diamonds
        // REMEMBER:  the card # is off-by-one from the face value
        Card firstnode = new Card();
        firstnode.setSuit(Card.DIAMOND);
        firstnode.setCard(2);
        System.out.println("The first node is: " + firstnode);

        // this is a super-basic JFrame, used only for really basic testing
        JFrame frame = new JFrame("Card");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(firstnode.getImage(), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);     
    }
}

1 个答案:

答案 0 :(得分:0)

对不起,我不知道为什么结果会有所不同。

在ImageIO.read()调用期间,loadBufferedImage方法中存在异常,该调用在img.getSubimage();处抛出NullPointerException。

可能的解决方法是在loadBufferedImage()中使用getResourceAsStream:

InputStream in = getClass().getResourceAsStream(IMAGEFILENAME);
img = ImageIO.read(in);
in.close();

请查看这是否适合您。