The Artima Developer Community
Sponsored Link

Java Answers Forum
how to create, store and use a graphic object...

2 replies on 1 page. Most recent reply: Jul 29, 2002 2:26 PM by Guido

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Guido

Posts: 38
Nickname: kiethb
Registered: May, 2002

how to create, store and use a graphic object... Posted: Jul 26, 2002 1:30 PM
Reply to this message Reply
Advertisement
I found a silly card dealing program in which I am trying to learn by enhancing it. In the process I found a class that I could use to place graphics into an APPLICATION, which is by no means an easy task if you are still learning this stuff. anyway, I decided that I wanted to use graphics for the cards instead of the words, so I modified the Card class to store not only the strings Face and Suit but a graphic object representation of the card itself... this way the card and picture were always together. only problem is, I am not sure how to get that graphic onto the application now... following are some snippets as to what I have done. it starts out with the Card class and the CardPanel class.

ultimately if someone can tell me how to intialize and use this portion of the Card object and the syntax involved to perform this correctly.


public Card( String f, String s, cardPanel r )
   {
      face = f;
      suit = s;
      rep = r;
   }
 
    public cardPanel getCard(){
		return rep;
    }
 
   public String toString() { 
	
	return face + " of " + suit + " including " + rep; 
   }
}
 
 
 
class cardPanel extends JPanel{
 
   private ImageIcon imageIcon;
 
   public cardPanel(File imageFile){
	super();
	imageIcon = new ImageIcon                           (imageFile.getAbsolutePath());
	setPreferredSize(new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight())); 
   }
 
   public cardPanel(String imageFileName){
	super();
	imageIcon = new ImageIcon(imageFileName);
	setPreferredSize(new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight())); 
   }
 
   public void paint(Graphics g){
	super.paintComponent(g);
	g.drawImage(imageIcon.getImage(),0,0,this);
   }
}
 


first I create the deck of cards

for ( int i = 0; i < deck.length; i++ ){
		File imageFile = new File(cardGifs[i]);
         	deck[ i ] = new Card( faces[ i % 13 ],
                               suits[ i / 13 ],new cardPanel(imageFile));


, then shuffle. next, the dealer deals 2 hands one to himself and one to me...

if ( mDealt1 != null ) {
    myHand[0] = mDealt1;
               		}
  else {
  status.setText("Shuffle cards to continue" );
  }


then when I go through each card in each hand, I want to extract just the graphic object (rep) and place that on the screen. like this: (it calls addComponent which takes care of the constraints and stuff)

        mDisplayCard1 = myHand[0].getCard();
      	addComponent(mDisplayCard1,4,1,1,1);
 


anyway, when I run this I get a nullPointer error, I know for a fact the exception output points to this part of the logic...

for completeness I will include my entire source and stack trace.

// Fig. 10.21: DeckOfCards.java
// Card shuffling and dealing program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
 
public class DeckOfCards extends JFrame {
   private Card deck[];
   private Card myHand[];
   private Card hisHand[];
   private int currentCard;
   private JButton dealButton, shuffleButton, discardButton;
   private JRadioButton dCard1,dCard2,dCard3,dCard4,dCard5;		 
   private cardPanel mDisplayCard1,mDisplayCard2,mDisplayCard3,mDisplayCard4,mDisplayCard5;
   private cardPanel hDisplayCard1,hDisplayCard2,hDisplayCard3,hDisplayCard4,hDisplayCard5;
   private JLabel status, dealerTag, playerTag;
   private int mCountFaces[];
   private int mCountSuits[];
   private int hCountFaces[];
   private int hCountSuits[];
   private GridBagLayout gbLayout;
   private GridBagConstraints gbConstraints;
   private Container container;
   
   public DeckOfCards()
   {
      super( "JPoker!" );
 
      String faces[] = { "Ace", "Deuce", "Three", "Four",
                         "Five", "Six", "Seven", "Eight",
                         "Nine", "Ten", "Jack", "Queen",
                         "King" };
      String suits[] = { "Hearts", "Diamonds",
                         "Clubs", "Spades" };
 
	String cardGifs[] = {"ah.gif","2h.gif","3h.gif","4h.gif","5h.gif","6h.gif","7h.gif",
	 		 	    "8h.gif","9h.gif","th.gif","jh.gif","qh.gif","kh.gif","ad.gif",
	 		 	    "2d.gif","3d.gif","4d.gif","5d.gif","6d.gif","7d.gif","8d.gif",
	 		 	    "9d.gif","td.gif","jd.gif","qd.gif","kd.gif","ac.gif","2c.gif",
	 		 	    "3c.gif","4c.gif","5c.gif","6c.gif","7c.gif","8c.gif","9c.gif",
	 		 	    "tc.gif","jc.gif","qc.gif","kc.gif","as.gif","2s.gif","3s.gif",
	 		 	    "4s.gif","5s.gif","6s.gif","7s.gif","8s.gif","9s.gif","ts.gif",
                       	    "js.gif","qs.gif","ks.gif"};
 
 
		 // set up counting arrays 
		 //these will be used by comparing string values of the cards and then adding
		 // one to their position in the array, can then analyze the array to 
		 // determine what we have in our hands.  the suits array is for calculating flushes
 
		 mCountFaces = new int[13];
		 mCountSuits = new int[4];
		 // his counting arrays
		 hCountFaces = new int[13];
		 hCountSuits = new int[4];
 
      	 deck = new Card[ 52 ];
		 // hold MY cards
      	 myHand = new Card[ 5 ];
		 // hold his cards
		 hisHand = new Card[ 5 ];
 
		 currentCard = -1;
		 // *******************************
		 // this creates the deck of cards
		 // *******************************
      	for ( int i = 0; i < deck.length; i++ ){
		File imageFile = new File(cardGifs[i]);
         	deck[ i ] = new Card( faces[ i % 13 ],
                               suits[ i / 13 ],new cardPanel(imageFile));
		 		 
		 
		 }
 
      	 container = getContentPane();
 		 gbLayout = new GridBagLayout();
		 container.setLayout( gbLayout );
		 gbConstraints = new GridBagConstraints();
		 
		 dealerTag = new JLabel("Dealer");
		 playerTag = new JLabel("Player 1");
		 		 
		 //gbConstraints.fill = GridBagConstraints.BOTH;
		 addComponent(dealerTag,1,3,1,1);
      	 addComponent(playerTag,3,3,1,1);
 
		 dCard1 = new JRadioButton();
		 dCard2 = new JRadioButton();
		 dCard3 = new JRadioButton();
		 dCard4 = new JRadioButton();
		 dCard5 = new JRadioButton();
		 
		 addComponent(dCard1,5,1,1,1);
		 addComponent(dCard2,5,2,1,1);
		 addComponent(dCard3,5,3,1,1);
		 addComponent(dCard4,5,4,1,1);
		 addComponent(dCard5,5,5,1,1);
		 		 
      	dealButton = new JButton( "Deal card" );
      	dealButton.addActionListener(
         
		new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               Card mDealt1 = dealCard();
		 		 if ( mDealt1 != null ) {
                  		//mDisplayCard1.setText( mDealt1.toString() );
             	 		myHand[0] = mDealt1;
               		}
		 		 else {
                  		//mDisplayCard1.setText( "NO MORE CARDS TO DEAL" );
                  		status.setText("Shuffle cards to continue" );
               		}
 
		   Card hDealt1 = dealCard();
		 		 if ( hDealt1 != null ) {
                  		//hDisplayCard1.setText( hDealt1.toString() );
             		 	hisHand[0] = hDealt1;
               		}
		 		 else {
                  		//hDisplayCard1.setText("NO MORE CARDS TO DEAL" );
                  		status.setText("Shuffle cards to continue" );
               		}
 
 
	         Card mDealt2 = dealCard();
		 		 if ( mDealt2 != null ) {
             		     //mDisplayCard2.setText( mDealt2.toString() );
             		     myHand[1] = mDealt2;
               		}
		 		 else {
                  		//mDisplayCard2.setText( "NO MORE CARDS TO DEAL" );
                  		status.setText("Shuffle cards to continue" );
               		}
 
		   Card hDealt2 = dealCard();
		 		 if ( hDealt2 != null ) {
                  		//hDisplayCard2.setText( hDealt2.toString() );
             		 	 hisHand[1] = hDealt2;
               		}
		 		 else {
                  		//hDisplayCard2.setText( "NO MORE CARDS TO DEAL" );
                  			status.setText("Shuffle cards to continue" );
               		}
 
               Card mDealt3 = dealCard();
		 		 if ( mDealt3 != null ) {
                  		//mDisplayCard3.setText( mDealt3.toString() );
                       		 myHand[2] = mDealt3;
		 		 		 }
		 		 else {
                  		//mDisplayCard3.setText( "NO MORE CARDS TO DEAL" );
                  		status.setText( "Shuffle cards to continue" );
               }
 
 		   Card hDealt3 = dealCard();
		 		 if ( hDealt3 != null ) {
					 //hDisplayCard3.setText( hDealt3.toString() );
                       		 hisHand[2] = hDealt3;
		 		  }
		 		 else {
                  		//hDisplayCard3.setText( "NO MORE CARDS TO DEAL" );
                  		status.setText( "Shuffle cards to continue" );
               		}
 
 
		   Card mDealt4 = dealCard();
		 		 if ( mDealt4 != null ) {
                  		//mDisplayCard4.setText( mDealt4.toString() );
                      		 myHand[3] = mDealt4;
		 		 }
		 		 else {
                  		//mDisplayCard4.setText( "NO MORE CARDS TO DEAL" );
                  		status.setText( "Shuffle cards to continue" );
               }
 
		   Card hDealt4 = dealCard();
		 		 if ( hDealt4 != null ) {
                  		//hDisplayCard4.setText( hDealt4.toString() );
                      		 hisHand[3] = hDealt4;
		 		 }
		 		 else {
                  		//hDisplayCard4.setText( "NO MORE CARDS TO DEAL" );
                  		status.setText( "Shuffle cards to continue" );
               }
 
 
		   Card mDealt5 = dealCard();
		 		 if ( mDealt5 != null ) {
             		     //mDisplayCard5.setText( mDealt5.toString() );
                      	      myHand[4] = mDealt5;
		 		 }
		 		 else {
                  		//mDisplayCard5.setText( "NO MORE CARDS TO DEAL" );
                  		status.setText( "Shuffle cards to continue" );
               		}
 
		   Card hDealt5 = dealCard();
		 		 if ( hDealt5 != null ) {
                  		//hDisplayCard5.setText( hDealt5.toString() );
                      		 hisHand[4] = hDealt5;
		 		 }
		 		 else {
                  		//hDisplayCard5.setText( "NO MORE CARDS TO DEAL" );
                  		status.setText( "Shuffle cards to continue" );
               		}
 
 
		 		 // this is just a test to print out to the console
		 		 for(int tempx = 0;tempx<5;tempx++){
		 		 		 System.out.println(myHand[tempx].toString());
		 		 }
		 		 // this is just a test to print out to the console
		 		 for(int tempy = 0;tempy<5;tempy++){
		 		 		 System.out.println(hisHand[tempy].toString());
		 		 }
 
            }
         }
      );
		 dealButton.setEnabled(false);
   
		 addComponent(dealButton,6,3,1,1);		 
 
		 discardButton = new JButton( "Discard" );
		 discardButton.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
              // put functionality for discard here 
		 		 		 System.out.println("discarded");
		 		 }
		    }
      );
		 addComponent(discardButton,6,5,1,1);
 
 
      	shuffleButton = new JButton( "Shuffle cards" );
      	shuffleButton.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               status.setText( "SHUFFLING ..." );
               shuffle();
               
            }
         }
      );
      	addComponent(shuffleButton,6,1,1,1);
		 		 		 
      	mDisplayCard1 = myHand[0].getCard();
      	addComponent(mDisplayCard1,4,1,1,1);
		 
      	status = new JLabel();
      	addComponent(status,7,1,1,5);
 
		 setSize( 400,400);  // set the window size
      show();               // show the window
   }
 
   public void shuffle()
   {
      currentCard = -1;
 
      for ( int i = 0; i < deck.length; i++ ) {
         int j =  ( int ) ( Math.random() * 52 );
         Card temp = deck[ i ];   // swap
         deck[ i ] = deck[ j ];   // the
         deck[ j ] = temp;        // cards
      }
 
      dealButton.setEnabled( true );
   }
 
   public Card dealCard()
   {
      if ( ++currentCard < deck.length )
         return deck[ currentCard ];
		 
      else {
         dealButton.setEnabled( false );
         return null;
      }
   }
 
   public void findOnePair(){}
 
   public void findTwoPair(){}
 
   public void findThreeOfAKind(){}
 
   public void findFourOfAKind(){}
 
   public void findFlush(){}
 
   public void findStraight(){}
 
   public void findFullhouse(){}
 
   
   private void addComponent(Component c, int row, int column, int width, int height){
 
		    gbConstraints.gridx = column;
		    gbConstraints.gridy = row;
 
		    gbConstraints.gridwidth = width;
		    gbConstraints.gridheight = height;
 
		    gbLayout.setConstraints(c,gbConstraints);
		    container.add(c);
 
   }
 
 
 
   public static void main( String args[] )
   {
      DeckOfCards app = new DeckOfCards();
 
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}
 
 
 
class Card {
   private String face;
   private String suit;
   private cardPanel rep;
		 
   public Card( String f, String s, cardPanel r )
   {
      face = f;
      suit = s;
      rep = r;
   }
 
    public cardPanel getCard(){
		return rep;
	}
 
   public String toString() { 
	
	return face + " of " + suit + " including " + rep; 
   
   }
}
 
 
 
class cardPanel extends JPanel{
 
   private ImageIcon imageIcon;
 
   public cardPanel(File imageFile){
	super();
	imageIcon = new ImageIcon(imageFile.getAbsolutePath());
	setPreferredSize(new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight())); 
   }
 
   public cardPanel(String imageFileName){
	super();
	imageIcon = new ImageIcon(imageFileName);
	setPreferredSize(new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight())); 
   }
 
   public void paint(Graphics g){
	super.paintComponent(g);
	g.drawImage(imageIcon.getImage(),0,0,this);
   }
}
 


Exception in thread "main" java.lang.NullPointerException
at DeckOfCards.<init>(DeckOfCards.java:258)
at DeckOfCards.main(DeckOfCards.java:362)


Jay Kandy

Posts: 77
Nickname: jay
Registered: Mar, 2002

Re: how to create, store and use a graphic object... Posted: Jul 27, 2002 12:10 PM
Reply to this message Reply
myCards[] array was declared but not inited. When I put this code
for ( int i = 0; i < myHand.length; i++ )
{
	java.util.Random r = new java.util.Random();
 
	int index = r.nextInt(cardGifs.length);
	File imageFile = new File(cardGifs[index]);
	myHand[ i ] = new Card( faces[ index % 13 ], suits[ index / 13 ],new cardPanel(imageFile));
}


after the lines

currentCard = -1;
// *******************************
// this creates the deck of cards
// *******************************


the window showed up, but I dont know if thats how its played!

Guido

Posts: 38
Nickname: kiethb
Registered: May, 2002

Re: how to create, store and use a graphic object... Posted: Jul 29, 2002 2:26 PM
Reply to this message Reply
well, it took me a little while to see what you were getting at. I thought everything had been created and initialized but after seeing your 'fix' in action I realized the flaw. the real issue was a design flaw. because I dont deal any cards upon startup. I deal after a shuffle. therefore, the the objects ARE null. so I just need to init them with a blank graphic object or something similar to show no cards have been dealt. thanks man! it's the silly stuff that will get ya!

Flat View: This topic has 2 replies on 1 page
Topic: java c++ communication Previous Topic   Next Topic Topic: Formatting number length

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use