Wasn't sure which subforum to put this in. It feels like it crosses a couple different aspects of Java.
So I have these two classes that I wrote a few months back. The Card class represents a single playing card and the Deck class is just an array of Card objects. I'm trying to build 4 JPanels, each with 13 cards. I have a function that builds an individual panel. It in turn calls a function to deal a single card. Each panel has 13 JButtons with a graphical representation of the card on it.
Here is the function that builds the panel.
private JPanel buildCardPanel() { //Panel to add elements to. JPanel returnPanel = new JPanel(); //JButton on which an individual card will be shown. JButton[] handButton = new JButton[13]; //A hand of 13 cards. Card[] hand = new Card[13]; returnPanel.setLayout(new GridLayout(1,13)); for(int i = 0; i < 13; i++) { //Deal a card. hand[i] = dealCard(); //Set that card's image icon on the button. System.out.println(hand[i].getImageIcon().toString()); handButton[i].setIcon(hand[i].getImageIcon()); returnPanel.add(handButton[i]); } return returnPanel; }
Here is the function that deals cards. It accesses a Deck object named starterDeck (I think baseball cards were on my mind when I came up with that name... it's kind of a stupid variable name) defined earlier. I realize that it doesn't prevent the same card from being drawn multiple times. I'll implement that later.
The Card.getImageIcon() method is a simple getter method:
public ImageIcon getImageIcon() { return this.cardIcon; }
But I keep getting a NullPointerException on the line that says handButton[i].setIcon(hand[i].getImageIcon()); which I don't understand.
If you notice the println statement before that, you probably realize that's just temporary for debugging purposes. It's returning a value. I get something like "javax.swing.ImageIcon@4ba2fc31", which matches what I get if I put a System.out.println(this.cardIcon); inside the Card.getImageIcon function.
So I'm really confused. hand[i].getImageIcon() seems to be returning an ImageIcon object. That object is being passed to handButton[i].setIcon(); So where the heck is the Null Pointer Exception coming from?