swing - Image filepath in Java GUI - NullPointerException -


this question has answer here:

i making simple card game , i'm trying use file paths .jpg files card images. getting nullpointerexception, new java , struggling understand means , for.

this output:

tie. error in nextcard computer wins! error in nextcard exception in thread "awt-eventqueue-0" java.lang.nullpointerexception     @ war.getplayercard(war.java:160)     @ wargui$playcardlistener.actionperformed(wargui.java:98) 

i have traced far:

war class:

public string getplayercard() {    return playerwarcard.getfilepath();  // error } 

called wargui:

playercard = new imageicon(game.getplayercard()); // error 

i have feeling problem getfilepath method in card class (marked @ bottom), i'm unsure , appreciate if confirm.

card class:

public class card  {          // suits    private int suit;                               public final static int spades = 1;    public final static int hearts = 2;    public final static int diamonds = 3;    public final static int clubs = 4;     // ranks    private int rank;     public final static int jack = 11;           public final static int queen = 12;           public final static int king = 13;    public final static int ace = 14;      string cardfilepath;                                  /**     constructor initializes card's rank , suit.     @param rank     @param suit    */     public card(int rank, int suit)     {       this.rank = rank;       this.suit = suit;            cardfilepath = "cardpics/" + suit + rank + ".jpg";    }     /**     other constructor initializes card's rank , suit.     @param othercard copied    */      public card(card othercard)     {       this.rank = othercard.rank;       this.suit = othercard.suit;    }     /**     getrank method returns int represents card's rank.     @return card's rank    */     public int getsuit()     {       return suit;    }     /**     getrank method returns int represents card's rank.     @return card's rank    */     public int getrank()     {       return rank;    }     /**    * returns description of card.    * @return name of card.    */      public string tostring()      {         return getrankasstring() + " of " + getsuitasstring();     }     /**     equals method compares rank of card rank of     card. if same, method returns true.     @return boolean    */     public boolean equals(card othercard )     {       return rank == othercard.rank;    }     /**     getsuitstring method returns card's suit string.     @return suitstring    */     public string getsuitasstring()     {       switch (suit)       {          case spades:   return "spades";          case hearts:   return "hearts";          case diamonds: return "diamonds";          case clubs:    return "clubs";          default:       return "invalid";       }    }     /**     getrankstring method returns card's rank.     @return rank    */     public string getrankasstring()     {       switch (rank)        {          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";          case 13:   return "king";          case 14:   return "ace";          default:   return "??";       }    }     /**     returns .jpg image of card     @return path image    */     public string getfilepath()     // error?    {        return cardfilepath;    } } 

attached reference war class:

import java.util.arraylist; import javax.swing.*;  public class war {    static cardpile warpile;    static cardpile player1 = new cardpile();    static cardpile player2 = new cardpile();     static card unseenplayercard;    static card unseencomputercard;    static card playerwarcard;    static card computerwarcard;     static string war = "false";     /**     constructor prepares, shuffles deck deals players.    */     public void war()     {       deck deck = new deck();       deck.shuffle();        while(deck.getsize() > 0)       {          player1.collectcard(deck.deal());          player2.collectcard(deck.deal());       }    }     /**     comparecards method compares rank of card determine winner     @param playerscard, computerscard     @return outcome    */     public static int comparecards(card playerscard, card computerscard)    {        if (playerscard.getrank() > computerscard.getrank())             {               player1.collectcard(playerscard);               player1.collectcard(computerscard);                system.out.println("player's card: " + playerscard.tostring() + "\ncomputer's card: " +                                   computerscard.tostring() + "\nyou win!");                return 1;             }              else if (playerscard.getrank() < computerscard.getrank())             {               player2.collectcard(playerscard);               player2.collectcard(computerscard);                system.out.println("your card: " + playerscard.tostring() + "\ncomputer's card: " +                                   computerscard.tostring() + "\nyou lose.");                return 2;             }              // if cards equal, war             else             {                 war = "true";                 system.out.println("your card: " + playerscard.tostring());                 system.out.println("computer's card: " + computerscard.tostring());                 joptionpane.showmessagedialog(null, "war!");                 beginwar(playerscard, computerscard);                 return 3;             }    }     /**     beginwar method draws war cards, compares determine     winner of war.     @param playerscard, computerscard    */     public static void beginwar(card playerscard, card computerscard)    {             // prize cards         unseenplayercard = player1.playcard();        unseencomputercard = player2.playcard();         // add cards winning pile        warpile.collectcard(playerscard);        warpile.collectcard(computerscard);        warpile.collectcard(unseenplayercard);        warpile.collectcard(unseencomputercard);         // determine winner        playerwarcard = player1.playcard();        computerwarcard = player2.playcard();         int outcome = comparecards(playerwarcard, computerwarcard);         if (outcome == '1')        {            system.out.println("you win war!");        }         if (outcome == '2')        {            system.out.println("you lose war.");        }    }     /**     computercardsleft method returns number of cards in     computer's hand.     @return computer hand size    */     public int computercardsleft()    {        return player2.getsize();    }     /**     playercardsleft method returns number of cards in     players's hand.     @return player hand size    */     public int playercardsleft()    {        return player1.getsize();    }     /**     getcomputercard method returns image path of     computer's card gui.     @return filepath    */     public string getcomputercard()    {        return computerwarcard.getfilepath();    }     /**     getplayercard method returns image path of     computer's card gui.     @return filepath    */     public string getplayercard()     {        return playerwarcard.getfilepath();       // error    }     /**     playerdraw method draws next card in player's pile.     @return card    */     public card playerdraw()    {        if (player1.getsize() < 1)          {           endgame();        }        return player1.nextcard();     }     /**     computerdraw method draws next card in computer's pile.    */     public card computerdraw()    {           if (player2.getsize() < 1)        {           endgame();        }         return player2.playcard();    }     /**     endgame method displays results.    */     public void endgame()    {         if (player1.getsize() > player2.getsize())               system.out.println("player wins!");         else if (player2.getsize() > player1.getsize())               system.out.println("computer wins!");         else               system.out.println("tie.");    }     /**     enoughcards method determins whether or not player meets minimum     card requirement.    */     public static boolean enoughcards(int n)    {       if (player1.getsize() < n || player2.getsize() < n)       {          return false;       }          return true;    }   } 

...and wargui

import javax.swing.*; import java.awt.*; import java.awt.event.*;  public class wargui extends jframe {      private wargui guigame;        private war game;                                                                              private jpanel rightplayerpanel;           // player                       private jpanel leftplayerpanel;            // computer    private jpanel buttonpanel;                // holds buttons                      private jpanel gamepanel;                  // main deck area     private jbutton playbutton;            private static jlabel backlabelleft;                           private static jlabel playercardlabel;                              private static jlabel computercardlabel;      private imageicon back;                    // icon backside of card    private imageicon blank;                   // place holder    private static imageicon playercard;              // player 1's current card    private static imageicon computercard;            // player 2's current card     private jtextfield playercardsleft;    private jtextfield computercardsleft;  //    static hand player1; //    static hand player2;     private card playerscard;    card computerscard;     private string war = "false";      string imagepath = "cardpics/back.jpg";                                   /**     constructor builds & adds panels contentpane.    */     public wargui()    {       // set contentpane       setlayout(new borderlayout());       settitle("game of war");       setsize(1100, 550);       setdefaultcloseoperation(windowconstants.exit_on_close);       setlocationrelativeto(null);        // build & add deck panel       assemblegamepanel();       add(gamepanel, borderlayout.center);              // build & add player panels       assembledeckspanel();       add(leftplayerpanel, borderlayout.west);       add(rightplayerpanel, borderlayout.east);        // build & add button panel       assemblebuttonpanel();       add(buttonpanel, borderlayout.south);        setvisible(true);        // prepare deck & player hands       game = new war();          // //welcome message //        joptionpane.showmessagedialog(null, "welcome!");    }     /**     playcardlistener tracks clicks on play card button. cards drawn, war status checked, scores , images adjusted.    */     private class playcardlistener implements actionlistener    {       public void actionperformed(actionevent e)       {          // regular gameplay          if (war.equals("false"))          {             card playerscard = game.playerdraw();                 card computerscard = game.computerdraw();                // update card images             playercard = new imageicon(game.getplayercard());    // error             playercardlabel.seticon(playercard);               computercard = new imageicon(computerscard.getfilepath());             computercardlabel.seticon(computercard);              // compare             game.comparecards(playerscard, computerscard);                          // // otherwise, update score  //             //if (!war.equals("true")) //             else //             { //                 // playercardsleft.settext("player's cards: " + (player1.getsize() - 1)); // //                 computercardsleft.settext("computer's cards: " + (player2.getsize() - 1)); //  //             }             playercardsleft.settext("player's cards: " + (game.playercardsleft() - 1));             computercardsleft.settext("computer's cards: " + (game.computercardsleft() - 1));           }           // war deckplay          // second click - face down card          else if (war.equals("true"))          {             // set icons card backside             playercardlabel.seticon(back);             computercardlabel.seticon(back);              war = "last";          }              // third click          else if (war.equals("last"))          {             // identify cards involved in war, update icons             computercard = new imageicon(game.getcomputercard());             computercardlabel.seticon(computercard);              playercard = new imageicon(game.getplayercard());             playercardlabel.seticon(playercard);              war = "final";          }           // war final          else if (war.equals("final"))          {             war = "false";              // update scores             playercardsleft.settext("player's cards: " + (game.playercardsleft()));             computercardsleft.settext("computer's cards: " + (game.computercardsleft()));          }          else             system.out.println("error");       }    }     /**     assemblegamepanel builds cardpanel - main deck area, cards displayed.    */     private void assemblegamepanel()    {       // place holder cards       blank = new imageicon();       playercardlabel = new jlabel(blank);       computercardlabel = new jlabel(blank);        // add labels cardpanel        gamepanel = new jpanel();       gamepanel.add(playercardlabel);       gamepanel.add(computercardlabel);       gamepanel.setpreferredsize(new dimension(545, 540));       gamepanel.setbackground(new color(0, 64, 0));    }     /**     assembledeckspanel method builds panel displays players' cardpiles.    */     private void assembledeckspanel()    {       // icons of card backside       = new imageicon(imagepath);        // add icons       backlabelleft = new jlabel();       backlabelleft.seticon(back);       jlabel backlabelright = new jlabel();       backlabelright.seticon(back);        // add labels panels       // right       rightplayerpanel = new jpanel();       rightplayerpanel.setpreferredsize(new dimension(150,220));       rightplayerpanel.add(backlabelright);       rightplayerpanel.setbackground(new color(0, 64, 0));       playercardsleft = new jtextfield("player's cards: 26", 13);       playercardsleft.seteditable(false);       rightplayerpanel.add(playercardsleft);        // left        leftplayerpanel = new jpanel();       leftplayerpanel.setpreferredsize(new dimension(150,220));       leftplayerpanel.add(backlabelleft);       leftplayerpanel.setbackground(new color(0, 64, 0));       computercardsleft = new jtextfield("computer's cards: 26", 13);        computercardsleft.seteditable(false);       leftplayerpanel.add(computercardsleft);     }     /**     assemblebuttonpanel method adds buttons button panel.    */     private void assemblebuttonpanel()    {       // create & add button       jbutton playcardbutton = new jbutton("play!");       playcardbutton.setpreferredsize(new dimension(150,80));       buttonpanel = new jpanel();       buttonpanel.add(playcardbutton);       buttonpanel.setbackground(new color(0, 64, 0));        // add event listeners buttons.       playcardbutton.addactionlistener(new playcardlistener());    }          /**     main method begins gui deck.    */     public static void main(string[] args)     {        wargui guigame = new wargui();    }  } 

edit: understand there problem somewhere else. such, post other classes...

cardpile

public class cardpile {    // create array hold player's pile, , parameters array.     private card[] cardpile;    private int front;    private int end;     /**     constructor creates empty pile capable of holding 52 cards.    */     public cardpile()    {       cardpile = new card[52];       front = 0;        end = 0;    }     /**     nextcard method returns card @ front of pile.     @return c    */     public card nextcard()    {       if (front == end)       {          system.out.println("error in nextcard");       }        card c = cardpile[front];       front++;       return c;       }     /**     collectcard method adds card pile.    */     public void collectcard(card c)     {       cardpile[end] = c;       end++;    }     public card playcard()    {       return nextcard();    }     /**     getsize method returns size of pile.     @return size    */     public int getsize()    {       int size = end - front;       return size;    }     /**     clear method clears pile of cards.    */     public void clear()    {       front = 0;       end = 0;    } } 

deck:

import java.util.*;  public class deck {    private card[] deck;    private int numcards;     /**     constructor creates deck of 52 cards    */     public deck()    {       deck = new card[52];       filldeck();    }     /**     filldeck method fills deck cards.    */     public void filldeck()    {       int index = 0;       (int q = 1; q <= 13; q++)       {          (int n = 1; n <= 4; n++)          {             deck[index] = new card(q, n);             index++;          }       }    }     /**     shuffle method shuffles deck.    */     public void shuffle()    {       (int sh = 0; sh < numcards - 1; sh++)       {          int r = myrandom(sh, numcards - 1);          card shufflecard = deck[sh];          deck[sh] = deck[r];          deck[r] = shufflecard;       }    }     /**     deal method deals players.     @return updated deck    */     public card deal()    {       if(numcards == 0)       {          return null;       }       numcards--;               return deck[numcards];         }     /**     getsize method returns size of deck     @return numcards in deck    */     public int getsize()    {       return numcards;    }     /**     myrandom method returns random number.     @return random number    */     private static int myrandom(int low, int high)    {       int random = (int)((high + 1 - low) * math.random() + low);       return random;    } } 

you have 2 constructors:

public card(int rank, int suit)     {       this.rank = rank;       this.suit = suit;            cardfilepath = "cardpics/" + suit + rank + ".jpg";    }     /**     other constructor initializes card's rank , suit.     @param othercard copied    */      public card(card othercard)     {       this.rank = othercard.rank;       this.suit = othercard.suit;    } 

if card instantiated rank , suite, set cardfilepath. if instantiate using othercard never set cardfilepath, meaning instance no string created , cardfilepath = null.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -