Reputation: 337
I'm trying to draw 5 cards onto a JPanel, but am having trouble with displaying the card images.
JLabel[] cards = {
new JLabel(CARD_BACK),
new JLabel(CARD_BACK),
new JLabel(CARD_BACK),
new JLabel(CARD_BACK),
new JLabel(CARD_BACK)
};
for(int i=0; i<cards.length; i++) {
cards[i].setBounds(60*i, 0, 150, 215);
}
for(JLabel z : cards)
auxHands.add(z);
auxHands.setLayout(null);
The above works fine and draws 5 card images, but when I try to condense the code like this:
JLabel[] cards = new JLabel[5];
Arrays.fill(cards, new JLabel(CARD_BACK));
for(int i=0; i<cards.length; i++) {
cards[i].setBounds(60*i, 0, 150, 215);
}
for(JLabel z : cards)
auxHands.add(z);
auxHands.setLayout(null);
it seems to only draw the last instance of the card. Eventually, I'm going to be drawing multiple hands, and it would seem tedious to keep instantiating a new JLabel[] as in the first code sample.
Here's a visual of what I mean: http://oipsl.freesuperhost.com/images/meh.png, the top half shows what it looks like when I execute the first snippet of code, while the bottom half is what it looks like with the second code snippet.
Upvotes: 2
Views: 218
Reputation: 1499780
This code:
Arrays.fill(cards, new JLabel(CARD_BACK));
only creates a single JLabel
. It then uses a reference to that single label for all elements in the array... hence the effect you're getting. It's equivalent to:
// Equivalent bad code
JLabel label = new JLabel(CARD_BACK);
JLabel[] cards = { label, label, label, label, label };
Hopefully you can see why that doesn't work.
You should use a loop which can populate the array with new labels and set the bounds at the same time. You can add it to auxHands
at the same time too:
JLabel[] cards = new JLabel[5];
for (int i = 0; i < cards.length; i++) {
JLabel label = new JLabel(CARD_BACK);
label.setBounds(60*i, 0, 150, 215);
auxHands.add(label);
cards[i] = label;
}
Note that unless you need the array elsewhere, you could do away with it completely:
for (int i = 0; i < 5; i++) {
JLabel label = new JLabel(CARD_BACK);
label.setBounds(60*i, 0, 150, 215);
auxHands.add(label);
}
Upvotes: 4