为什么我的小组不会画卡?

时间:2014-01-14 17:05:16

标签: java swing jpanel paintcomponent

我正在尝试将Fish转换为GUI版本,但每当我点击编译时,卡片面板都不会显示。它只带来一个小的绿色和黑色方块。它实际上并没有绘制卡片。我的代码如下:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class goFishCards {

  static int die1 = (int)(Math.random()*6) + 1; 
  static int die2= (int)(Math.random()*6) + 1;
  static JLabel welcome= new JLabel ("Welcome to Go Fish");
  static JLabel rollMessage= new JLabel ("Whoever has the highest roll goes first!");
  static JLabel computerMessage= new JLabel ("Your opponent's roll is...");
  static JLabel humanMessage= new JLabel ("Your roll is...");
  static JLabel outcome= new JLabel ("The person who goes first is "); 
  static boolean computersMove= true;
  static boolean humanMove=true;  
  static Deck myDeck = new Deck(); 
  static Hand userHand = new Hand (); 
  static Hand computerHand = new Hand (); 

  public static class drawComputerDice extends JPanel {
    public void paintComponent(Graphics g) {
      super.paintComponent(g);    
      this.setBackground(new Color(255,192,203));
      drawComputerDie(g, die1, 3,3);
    }//end of paintComponent.
    void drawComputerDie(Graphics g, int val, int x, int y) {
      g.setColor(Color.white);
          g.fillRect(x, y, 35, 35);
          g.setColor(Color.black);
          g.drawRect(x, y, 34, 34);
          if (val > 1)  // upper left dot
            g.fillOval(x+3, y+3, 9, 9);
          if (val > 3)  // upper right dot
             g.fillOval(x+23, y+3, 9, 9);
          if (val == 6) // middle left dot
            g.fillOval(x+3, y+13, 9, 9);
          if (val % 2 == 1) // middle dot (for odd-numbered val's)
            g.fillOval(x+13, y+13, 9, 9);
          if (val == 6) // middle right dot
            g.fillOval(x+23, y+13, 9, 9);
          if (val > 3)  // bottom left dot
            g.fillOval(x+3, y+23, 9, 9);
          if (val > 1)  // bottom right dot
            g.fillOval(x+23, y+23, 9,9);
          repaint();
    }//end of drawDie.  
  }//end of class drawDice.   
  public static class drawHumanDice extends JPanel {
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      this.setBackground(new Color(255,192,203));
      drawHumanDie(g, die2, 3,3);
    }//end of paintComponent.
    void drawHumanDie(Graphics g, int val, int x, int y) {
      g.setColor(Color.white);
          g.fillRect(x, y, 35, 35);
          g.setColor(Color.black);
          g.drawRect(x, y, 34, 34);
          if (val > 1)  // upper left dot
            g.fillOval(x+3, y+3, 9, 9);
          if (val > 3)  // upper right dot
            g.fillOval(x+23, y+3, 9, 9);
          if (val == 6) // middle left dot
            g.fillOval(x+3, y+13, 9, 9);
          if (val % 2 == 1) // middle dot (for odd-numbered val's)
            g.fillOval(x+13, y+13, 9, 9);
          if (val == 6) // middle right dot
            g.fillOval(x+23, y+13, 9, 9);
          if (val > 3)  // bottom left dot
            g.fillOval(x+3, y+23, 9, 9);
          if (val > 1)  // bottom right dot
            g.fillOval(x+23, y+23, 9,9);
          repaint();
    }
  }  

  public static class drawCards extends JPanel{
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      this.setBackground(new Color (0,0,0));

      for (int i=0; i < userHand.getCardCount(); i++)
        drawCards(g, userHand.getCard(i), 10 + i * 90, 160);
      for (int i=0; i <computerHand.getCardCount(); i++)
        drawCards(g, computerHand.getCard(i), 10 + i* 90,30);
      repaint();
    }//end of paintComponent.

    void drawCards(Graphics g, Card card, int x, int y) {
         if (card == null) { // Draw a face-down card
           g.setColor(Color.blue);
            g.fillRect(x,y,80,100);
            g.setColor(Color.white);
            g.drawRect(x+3,y+3,73,93);
            g.drawRect(x+4,y+4,71,91);
                repaint();
         }
         else {
           g.setColor(Color.white);
            g.fillRect(x,y,80,100);
            g.setColor(Color.gray);
            g.drawRect(x,y,79,99);
            g.drawRect(x+1,y+1,77,97);
            if (card.getSuit() == Card.DIAMONDS || card.getSuit() == Card.HEARTS)
              g.setColor(Color.red);

            else
              g.setColor(Color.black);
            g.drawString(card.getValueAsString(), x + 10, y + 30);
            g.drawString("of", x+ 10, y + 50);
            g.drawString(card.getSuitAsString(), x + 10, y + 70);
            repaint();
         }
       }  // end drawCard()
  }


  public static void main (String []args) {    
    myDeck.shuffle();
    for (int i = 0; i < 2; i++) {
      computerHand.addCard(myDeck.dealCard());
      userHand.addCard(myDeck.dealCard());
      System.out.print(userHand.getCard(i).getSuitAsString());
    }

    drawComputerDice dice1= new drawComputerDice();
    drawHumanDice dice2= new drawHumanDice();

    drawCards cards = new drawCards();

    welcome.setFont(new Font ("Times New Roman", Font.BOLD,35));
    welcome.setForeground(new Color (147,112,219));

    rollMessage.setFont(new Font ("Myriad Web Pro", Font.BOLD,15));
    rollMessage.setForeground(new Color(0,0,0));

    ImageIcon table= new ImageIcon ("cardTable.jpg");
    JLabel cardTable= new JLabel(table);

    JPanel picture= new JPanel();
    picture.setBackground(new Color(255,192,203));
    picture.add(cardTable);    

    JPanel dicePanel= new JPanel();
    dicePanel.setLayout(new GridLayout(0,1));
    dicePanel.setBackground(new Color(255,192,203));
    dicePanel.add(welcome, BorderLayout.NORTH);
    dicePanel.add(rollMessage);
    dicePanel.add(computerMessage);
    dicePanel.add(dice1);
    dicePanel.add(humanMessage);
    dicePanel.add(dice2);

    JPanel cardPanel = new JPanel();
    cardPanel.setLayout(new FlowLayout());
    cardPanel.setBackground(new Color(0,120,0));
    cardPanel.add(cards);
    cardPanel.setPreferredSize(new Dimension(460,310));

    JPanel mainPanel= new JPanel();
    mainPanel.setLayout(new FlowLayout());
    mainPanel.setBackground(new Color(255,192,203));
    mainPanel.add(picture);   
    mainPanel.add(dicePanel);
    mainPanel.add(cardPanel);

    JFrame window= new JFrame ("Go Fish!");
    window.setContentPane(mainPanel);
    window.setSize(500,500);
    window.setLocation(500,500);
    window.setVisible(true);
    window.setResizable(true);
  }
}//end of class.

卡:

/**
 * An object of type Card represents a playing card from a
 * standard Poker deck, including Jokers.  The card has a suit, which
 * can be spades, hearts, diamonds, clubs, or joker.  A space, heart,
 * diamond, or club has one of the 13 values: ace, 2, 3, 4, 5, 6, 7,
 * 8, 9, 10, jack, queen, or king.  Note that "ace" is considered to be
 * the smallest value.  A joker can also have an associated value; 
 * this value can be anything and can be used to keep track of several
 * different jokers.
 */

public class Card {

   public final static int SPADES = 0;       // Codes for the 4 suits, plus Joker.
   public final static int HEARTS = 1;
   public final static int DIAMONDS = 2;
   public final static int CLUBS = 3;
   public final static int JOKER = 4;

   public final static int ACE = 1;          // Codes for the non-numeric cards.
   public final static int JACK = 11;        //   Cards 2 through 10 have their 
   public final static int QUEEN = 12;       //   numerical values for their codes.
   public final static int KING = 13;

   /**
    * This card's suit, one of the constants SPADES, HEARTS, DIAMONDS,
    * CLUBS, or JOKER.  The suit cannot be changed after the card is
    * constructed.
    */
   private final int suit; 

   /**
    * The card's value.  For a normal cards, this is one of the values
    * 1 through 13, with 1 representing ACE.  For a JOKER, the value
    * can be anything.  The value cannot be changed after the card
    * is constructed.
    */
   private final int value;

   /**
    * Creates a Joker, with 1 as the associated value.  (Note that
    * "new Card()" is equivalent to "new Card(1,Card.JOKER)".)
    */
   public Card() {
      suit = JOKER;
      value = 1;
   }

   /**
    * Creates a card with a specified suit and value.
    * @param theValue the value of the new card.  For a regular card (non-joker),
    * the value must be in the range 1 through 13, with 1 representing an Ace.
    * You can use the constants Card.ACE, Card.JACK, Card.QUEEN, and Card.KING.  
    * For a Joker, the value can be anything.
    * @param theSuit the suit of the new card.  This must be one of the values
    * Card.SPADES, Card.HEARTS, Card.DIAMONDS, Card.CLUBS, or Card.JOKER.
    * @throws IllegalArgumentException if the parameter values are not in the
    * Permissible ranges
    */
   public Card(int theValue, int theSuit) {
      if (theSuit != SPADES && theSuit != HEARTS && theSuit != DIAMONDS && 
            theSuit != CLUBS && theSuit != JOKER)
         throw new IllegalArgumentException("Illegal playing card suit");
      if (theSuit != JOKER && (theValue < 1 || theValue > 13))
         throw new IllegalArgumentException("Illegal playing card value");
      value = theValue;
      suit = theSuit;
   }

   /**
    * Returns the suit of this card.
    * @returns the suit, which is one of the constants Card.SPADES, 
    * Card.HEARTS, Card.DIAMONDS, Card.CLUBS, or Card.JOKER
    */
   public int getSuit() {
      return suit;
   }

   /**
    * Returns the value of this card.
    * @return the value, which is one the numbers 1 through 13, inclusive for
    * a regular card, and which can be any value for a Joker.
    */
   public int getValue() {
      return value;
   }

   /**
    * Returns a String representation of the card's suit.
    * @return one of the strings "Spades", "Hearts", "Diamonds", "Clubs"
    * or "Joker".
    */
   public String getSuitAsString() {
      switch ( suit ) {
      case SPADES:   return "Spades";
      case HEARTS:   return "Hearts";
      case DIAMONDS: return "Diamonds";
      case CLUBS:    return "Clubs";
      default:       return "Joker";
      }
   }

   /**
    * Returns a String representation of the card's value.
    * @return for a regular card, one of the strings "Ace", "2",
    * "3", ..., "10", "Jack", "Queen", or "King".  For a Joker, the 
    * string is always numerical.
    */
   public String getValueAsString() {
      if (suit == JOKER)
         return "" + value;
      else {
         switch ( value ) {
         case 1:   return "Ace";
         case 2:   return "2";
         case 3:   return "3";
         case 4:   return "4";
         case 5:   return "5";
         case 6:   return "6";
         case 7:   return "7";
         case 8:   return "8";
         case 9:   return "9";
         case 10:  return "10";
         case 11:  return "Jack";
         case 12:  return "Queen";
         default:  return "King";
         }
      }
   }

   /**
    * Returns a string representation of this card, including both
    * its suit and its value (except that for a Joker with value 1,
    * the return value is just "Joker").  Sample return values
    * are: "Queen of Hearts", "10 of Diamonds", "Ace of Spades",
    * "Joker", "Joker #2"
    */
   public String toString() {
      if (suit == JOKER) {
         if (value == 1)
            return "Joker";
         else
            return "Joker #" + value;
      }
      else
         return getValueAsString() + " of " + getSuitAsString();
   }


} // end class Card

手:

/**
 * An object of type Hand represents a hand of cards.  The
 * cards belong to the class Card.  A hand is empty when it
 * is created, and any number of cards can be added to it.
 */

import java.util.ArrayList;

public class Hand {

   private ArrayList hand;   // The cards in the hand.

   /**
    * Create a hand that is initially empty.
    */
   public Hand() {
      hand = new ArrayList();
   }

   /**
    * Remove all cards from the hand, leaving it empty.
    */
   public void clear() {
      hand.clear();
   }

   /**
    * Add a card to the hand.  It is added at the end of the current hand.
    * @param c the non-null card to be added.
    * @throws NullPointerException if the parameter c is null.
    */
   public void addCard(Card c) {
      if (c == null)
         throw new NullPointerException("Can't add a null card to a hand.");
      hand.add(c);
   }

   /**
    * Remove a card from the hand, if present.
    * @param c the card to be removed.  If c is null or if the card is not in 
    * the hand, then nothing is done.
    */
   public void removeCard(Card c) {
      hand.remove(c);
   }

   /**
    * Remove the card in a specified position from the hand.
    * @param position the position of the card that is to be removed, where
    * positions are starting from zero.
    * @throws IllegalArgumentException if the position does not exist in
    * the hand, that is if the position is less than 0 or greater than
    * or equal to the number of cards in the hand.
    */
   public void removeCard(int position) {
      if (position < 0 || position >= hand.size())
         throw new IllegalArgumentException("Position does not exist in hand: "
               + position);
      hand.remove(position);
   }

   /**
    * Returns the number of cards in the hand.
    */
   public int getCardCount() {
      return hand.size();
   }

   /**
    * Gets the card in a specified position in the hand.  (Note that this card
    * is not removed from the hand!)
    * @param position the position of the card that is to be returned
    * @throws IllegalArgumentException if position does not exist in the hand
    */
   public Card getCard(int position) {
      if (position < 0 || position >= hand.size())
         throw new IllegalArgumentException("Position does not exist in hand: "
               + position);
       return (Card)hand.get(position);
   }

   /**
    * Sorts the cards in the hand so that cards of the same suit are
    * grouped together, and within a suit the cards are sorted by value.
    * Note that aces are considered to have the lowest value, 1.
    */
   public void sortBySuit() {
      ArrayList newHand = new ArrayList();
      while (hand.size() > 0) {
         int pos = 0;  // Position of minimal card.
         Card c = (Card)hand.get(0);  // Minimal card.
         for (int i = 1; i < hand.size(); i++) {
            Card c1 = (Card)hand.get(i);
            if ( c1.getSuit() < c.getSuit() ||
                    (c1.getSuit() == c.getSuit() && c1.getValue() < c.getValue()) ) {
                pos = i;
                c = c1;
            }
         }
         hand.remove(pos);
         newHand.add(c);
      }
      hand = newHand;
   }

   /**
    * Sorts the cards in the hand so that cards of the same value are
    * grouped together.  Cards with the same value are sorted by suit.
    * Note that aces are considered to have the lowest value, 1.
    */
   public void sortByValue() {
      ArrayList newHand = new ArrayList();
      while (hand.size() > 0) {
         int pos = 0;  // Position of minimal card.
         Card c = (Card)hand.get(0);  // Minimal card.
         for (int i = 1; i < hand.size(); i++) {
            Card c1 = (Card)hand.get(i);
            if ( c1.getValue() < c.getValue() ||
                    (c1.getValue() == c.getValue() && c1.getSuit() < c.getSuit()) ) {
                pos = i;
                c = c1;
            }
         }
         hand.remove(pos);
         newHand.add(c);
      }
      hand = newHand;
   }

   public void shuffle() {
      for ( int i = hand.size()-1; i > 0; i-- ) {
         int rand = (int)(Math.random()*(hand.size()));
         Card temp = getCard(rand);//card represented by random number;
         hand.remove(rand);//remove card represented by random number
         hand.add(temp);//add temp card to hand
      }
   }


}

甲板:

/**
 *  An object of type Deck represents a deck of playing cards.  The deck
 *  is a regular poker deck that contains 52 regular cards and that can
 *  also optionally include two Jokers.
 */
public class Deck {

   /**
    * An array of 52 or 54 cards.  A 54-card deck contains two Jokers,
    * in addition to the 52 cards of a regular poker deck.
    */
   private Card[] deck;

   /**
    * Keeps track of the number of cards that have been dealt from
    * the deck so far.
    */
   private int cardsUsed;

   /**
    * Constructs a regular 52-card poker deck.  Initially, the cards
    * are in a sorted order.  The shuffle() method can be called to
    * randomize the order.  (Note that "new Deck()" is equivalent
    * to "new Deck(false)".)
    */
   public Deck() {
      this(false);  // Just call the other constructor in this class.
   }

   /**
    * Constructs a poker deck of playing cards, The deck contains
    * the usual 52 cards and can optionally contain two Jokers
    * in addition, for a total of 54 cards.   Initially the cards
    * are in a sorted order.  The shuffle() method can be called to
    * randomize the order.
    * @param includeJokers if true, two Jokers are included in the deck; if false,
    * there are no Jokers in the deck.
    */
   public Deck(boolean includeJokers) {
      if (includeJokers)
         deck = new Card[54];
      else
         deck = new Card[52];
      int cardCt = 0; // How many cards have been created so far.
      for ( int suit = 0; suit <= 3; suit++ ) {
         for ( int value = 1; value <= 13; value++ ) {
            deck[cardCt] = new Card(value,suit);
            cardCt++;
         }
      }
      if (includeJokers) {
         deck[52] = new Card(1,Card.JOKER);
         deck[53] = new Card(2,Card.JOKER);
      }
      cardsUsed = 0;
   }

   /**
    * Put all the used cards back into the deck (if any), and
    * shuffle the deck into a random order.
    */
   public void shuffle() {
      for ( int i = deck.length-1; i > 0; i-- ) {
         int rand = (int)(Math.random()*(i+1));
         Card temp = deck[i];
         deck[i] = deck[rand];
         deck[rand] = temp;
      }
      cardsUsed = 0;
   }

   /**
    * As cards are dealt from the deck, the number of cards left
    * decreases.  This function returns the number of cards that
    * are still left in the deck.  The return value would be
    * 52 or 54 (depending on whether the deck includes Jokers)
    * when the deck is first created or after the deck has been
    * shuffled.  It decreases by 1 each time the dealCard() method
    * is called.
    */
   public int cardsLeft() {
      return deck.length - cardsUsed;
   }

   /**
    * Removes the next card from the deck and return it.  It is illegal
    * to call this method if there are no more cards in the deck.  You can
    * check the number of cards remaining by calling the cardsLeft() function.
    * @return the card which is removed from the deck.
    * @throws IllegalStateException if there are no cards left in the deck
    */
   public Card dealCard() {
      if (cardsUsed == deck.length)
         throw new IllegalStateException("No cards are left in the deck.");
      cardsUsed++;
      return deck[cardsUsed - 1];
      // Programming note:  Cards are not literally removed from the array
      // that represents the deck.  We just keep track of how many cards
      // have been used.
   }

   /**
    * Test whether the deck contains Jokers.
    * @return true, if this is a 54-card deck containing two jokers, or false if
    * this is a 52 card deck that contains no jokers.
    */
   public boolean hasJokers() {
      return (deck.length == 54);
   }

} // end class Deck

1 个答案:

答案 0 :(得分:2)

知道这就是问题所在。我只是想先测试一下。但是发生的事情是你的面板没有首选尺寸,所以什么都不会出现。如果您覆盖getPreferredSize()中的drawCards,则会显示。

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 400);
    }

只需在DrawCards中的某处添加以上内容即可。您可以将Dimension设置为您想要的任何大小。我只是使用上面的测试,它显示。

之前 getPreferredSize()

enter image description here

AFTER getPreferredSize()

enter image description here


作为旁注,您应该始终遵循Java命名约定。班级名称以大写字母开头。