JSwanson
JSwanson

Reputation: 3

Java Repaint method creates new objects on top of old ones

This is probably a stupid question but I can not seem to either remember how to stop the program from doing this or I never learned it.

I'm creating a blackjack game which draws random cards with the paintComponent. When the hit button is clicked, I want it to draw the next card and generate the new total. However, whenever I click the hit button, it draws the new card perfect, but it then creates all new cards on top of my already drawn cards.

How do I stop the repaint method from picking new random cards and keep them the same throughout the program? I should mention, all the cards are stored in an array and are called to with a random number generator. Also, this happens when I resize the java window.

If asked, I will post the code but I feel like this has a simple solution.

Upvotes: 0

Views: 192

Answers (1)

wattostudios
wattostudios

Reputation: 8764

You will need to move your 'select random card' logic outside of the paint method.

It might be a better idea to calculate all the cards in your array when you first build it, rather than selecting randomly at paint time. In other words, when you create the 'deck' array, build the entire deck so that every card knows what they are, before the user even begins to be dealt any cards from the deck. This way, there is no risk of them changing during gameplay. If you're only talking about 52 cards, or a small multiple of 52 cards, then the array is still pretty small and it'll be quick to randomise the entire array.

Alternatively, you could put a check on your "select random card" method that says something like this...

int cardValue = -1;

paintComponent(){
    if (cardValue == -1){
        cardValue = drawRandomCard();
    }
    // now paint it.
}

ie - restrict the drawRandomCard() to only run if the card doesn't already have a value.

Ultimately though, the best solution would be to completely separate the painting code from the logic - its bad coding practice for GUI activities like painting to be mixed in with programming logic.

Upvotes: 1

Related Questions