简体   繁体   中英

Add images to deck of cards - JAVA

im quite new to this site xD

Im trying to create a cards game in Java but im having some problems to create a deck with cards images. I created 2 classes: Deck and Card. In the Card class i put the following code

public static final int SPADE   = 4;
public static final int HEART   = 3;
public static final int CLUB    = 2;
public static final int DIAMOND = 1;

private static final String[] Suit = { "*", "d", "c", "h", "s"};
private static final String[] Rank = { "*", "A", "2", "3", "4",
           "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};       

private int cardValue;

public Card( int suit, int rank)
{
 if ( rank == 1 )
    cardValue = 14*10 + suit;      // Give Ace the rank 14
 else
    cardValue = rank*10 + suit;
}

In the Deck class i put the constructor to create the deck of 52 cards:

           private Card[] deckOfCards;         
       public static final int NCARDS = 52;

      public Deck( )
      {
         deckOfCards = new Card[NCARDS]; 

         int i=0;
         for ( int suit = Card.DIAMOND; suit <= Card.SPADE; suit++ )       {          
            for ( int rank = 1; rank <= 13; rank++,i++ ){
            deckOfCards[i] = new Card(suit, rank); 
            }
          }

      }

I also created the methods to shuffle and deal cards but i can't manage to associate to deckOfCards the relative images of each card. Could someone please help me? :)

Thanks in advance!

Another option is to use Unicode characters depicting playing cards . That way you could just use a string to store the character representing the card, and display it, as long as you use a font that supports it.

There are many ways to add image in Java. This is just one of the way (may not be the best), but it gives you an idea how to associate images to your objects.

//Create Objects
CardClass[] cardObj = new CardClass[52];

//Interface definition
String path = "your path name";
ImageIcon image = new ImageIcon();
JLabel label = new JLabel();
JPanel card = new JPanel();

image = new ImageIcon (path + cardObj[0].strImage);   //where strImage is attribute of CardClass
label = new JLabel (image);
card.add(label);

Note: you can't paste all my codes and expect it to work magically. Here I am trying to explain how you could associate object's attribute and use it when inserting an image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM