Currently I'm trying to make Video Poker. So far it consists of 2 classes: Card with int value, char suit, and boolean checked. Card is a JButton. Then Deck with a stack of Card objects.
The JButton in the VideoPoker class just won't update the ImageIcon when I draw a card, and I can't figure out why for the life of me. It updates it when I want the background image and then again when I want the original image, so why not a new card?
below is my code
import javax.swing.*;
import java.awt.event.*;
public class VideoPoker extends JPanel implements ActionListener {
private Deck deck;
private Card[] cards;
private JButton draw;
private final int MAXCARDS = 5;
public VideoPoker() {
deck = new Deck();
cards = new Card[MAXCARDS];
for(int i = 0; i < MAXCARDS; i++) {
cards[i] = deck.Draw();
cards[i].addActionListener(this);
add(cards[i]);
cards[i].setIcon(new ImageIcon
("Cards/" + cards[i].getValue() +
cards[i].getSuit() + ".png"));
}
draw = new JButton("Draw");
draw.addActionListener(this);
add(draw);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == draw) {
int checked = 0;
for(int i = 0; i < MAXCARDS; i++) {
if(cards[i].getChecked()) {
cards[i] = deck.Draw();
cards[i].setIcon(new ImageIcon
("Cards/" + cards[i].getValue() +
cards[i].getSuit() + ".png"));
checked++;
}
}
}
if(e.getSource() instanceof Card) {
Card source = (Card)e.getSource();
if(!source.getChecked()) {
source.setChecked(true);
source.setIcon(new ImageIcon("Cards/back.png"));
}
else {
source.setChecked(false);
source.setIcon(new ImageIcon
("Cards/" + source.getValue() +
source.getSuit() + ".png"));
}
}
}
It looks like the problem is caused by not adding the newly drawn card to the VideoPoker panel. When the draw event is handled, items in the cards array can be replaced, but these card/button objects are not yet added to the panel:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == draw) {
int checked = 0;
for(int i = 0; i < MAXCARDS; i++) {
if(cards[i].getChecked()) {
cards[i] = deck.Draw();
cards[i].setIcon(new ImageIcon
("Cards/" + cards[i].getValue() +
cards[i].getSuit() + ".png"));
checked++;
}
}
}
if(e.getSource() instanceof Card) {
// ...
}
}
When you remove the old card from the panel just before getting a new one and add the new card to the panel after that, the card changes on the screen as well.
remove(cards[i]);
cards[i] = deck.Draw();
add(cards[i]);
There is still some work to do because the card needs to be added at the right position.
You can also change your design and use a CardButton that has a reference to a card instead of having a Card that is a button. That way you can have five fixed CardButtons and let these reference the right Card objects, making the buttons and cards less tightly coupled.