【问题标题】:Add images to deck of cards - JAVA将图像添加到卡片组 - JAVA
【发布时间】:2014-06-07 17:16:17
【问题描述】:

我对这个网站很陌生 xD

我正在尝试用 Java 创建一个纸牌游戏,但在创建带有纸牌图像的牌组时遇到了一些问题。我创建了 2 个类:Deck 和 Card。在 Card 类中,我输入以下代码

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;
}

在 Deck 类中,我使用构造函数来创建一副 52 张卡片:

           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); 
            }
          }

      }

我还创建了洗牌和发牌的方法,但我无法将每张牌的相关图像与 deckOfCards 相关联。有人可以帮我吗? :)

提前致谢!

【问题讨论】:

  • 在您的对象中添加一个字符串变量,例如 strImage,其中存储图像名称,例如 queen_club.png,并且在调用图像时,只需从对象的变量中调用。
  • 你能解释一下吗? :) 你的意思是在我的 Card 方法中创建一个新的字符串变量?以及如何将图像存储在字符串中?
  • 添加一个属性来存储图片的名称,不能将图片存储为字符串。当您准备好添加图像时,只需从对象的属性中调用。请参阅下面的解决方案。

标签: java swing


【解决方案1】:

另一种选择是使用Unicode characters depicting playing cards。这样你就可以使用一个字符串来存储代表卡片的字符,并显示它,只要你使用支持它的字体。

【讨论】:

    【解决方案2】:

    在 Java 中有很多方法可以添加图像。这只是其中一种方式(可能不是最好的),但它让您了解如何将图像与您的对象相关联。

    //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);
    

    注意:您不能粘贴我的所有代码并期望它神奇地工作。在这里,我试图解释如何关联对象的属性并在插入图像时使用它。

    【讨论】:

    • 在你的路径名中我应该添加图像所在文件夹的路径,对吧?我怎样才能得到它,我必须写它?我在 Mac 上。谢谢:)
    • 我不确定 abt mac,但应该是一样的。为什么不先尝试编写路径并查看它是否有效。
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 2018-12-02
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多