I'm working on a Blackjack game in Java. I have several classes (Card, Shoe, Player, etc) and also a JComponent defined as follows:
Public class DisplayCard extends JComponent {
private ArrayList<Card> mCards;
public DisplayCard(){
mCards = new ArrayList<Card>();
}
public void append(ArrayList<Card> newCards){
mCards = newCards;
repaint();
}
public void paintComponent(Graphics g){
for (Card card : mCards) {
g.drawImage(card.getBuffImage(),10,10,null);
}
}
}
In my driver class, I have a JPanel (mPlayerPanel). I add the DisplayCard component to the Panel, create an array of cards, and use append() to update the list. The partial implementation is:
DisplayCard playerDisp = new DisplayCard();
Shoe tableShoe = new Shoe(1);
ArrayList<Card> cards = new ArrayList<Card>();
//Adds three cards to arraylist
cards.add(tableShoe.getNextCard());
cards.add(tableShoe.getNextCard());
cards.add(tableShoe.getNextCard());
mPlayerPanel.add(playerDisp,new GridConstraints()); //need "GridConstraints" to appease Intellij
playerDisp.append(cards);
I do not get any errors when I run this code. However, it does not paint anything onto the mPlayerPanel. Is there something obvious that I am doing wrong to make these BufferedImages not paint (NOTE: I'm aware they if they did print they would all be on top of each other. I wrote the code as a test to paint the BufferedImage before dealing with positioning).
Thanks in advance.
mPlayerPanel.add(playerDisp,new GridConstraints());
You are adding your DisplayCard to a panel using a GridBagLayout. The problem is the size of you component is (0, 0).
You need to override the getPreferredSize()
method of the DisplayCard class to return a reasonable value which would basically be the size of the image(s) you want to paint.
Instead of doing custom painting and managing the preferred size of your component, another option is to use a JLabel with an IconImage for all you cards. Then you can add the labels to a panel using an appropriate layout manager.
If you want your cards overlap one another you can use the Overlap Layout.