Tracking score in game

I am having a problem trying to keep track of score for players.  I need to be able to add mulitple players and manage the number of correct matches. I setup a JTextArea for the Player info, including the score, but I am unsure how to go about updating it.

Also I am having an issue with getting the JButton to restart the game to work as well, again not sure where to start.

Any help or direction is always appreicated.

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

      public class GameGUI extends JFrame implements ActionListener
            JPanel imagePanel;                                          // Panel for the images on buttons.
            JTextArea playerInfo;                                    // JTextArea for Player Information.
            JButton [] imageButton;                                    // Array of buttons to hold images.
            ImageIcon [] imageOnButton;                              // Array of imageIcons.
            Players [] playerArray = new Players [10];      // Array for Player information.
            ImageIcon imageNull;                                    // Null image for blank button.
            int status =1;                                                // Flag for when button selected.
            int indexOfFirst = 0;                                    // Temp index for image comparison.
            int lastPlayer = 0;
            int prompt;
            int currentTurn = 0;      
            private JButton startButton, closeButton;
            // Array of image file names to be used to create imageIcons to be shown on
            // the buttons.
            String [] images = {"apple.gif", "ball.gif", "bannana.gif", "bear.gif", "bird.gif", "bug.gif",
                        "butterfly.gif", "cake.gif", "cat.gif", "dog.gif", "doll.gif", "dragon.gif", "duck.gif",
                        "elephant.gif", "fish.gif", "flower.gif", "frog.gif", "gift.gif", "hat.gif", "hotdog.gif",
                        "jackinthebox.gif", "keys.gif", "pizza.gif", "plane.gif", "rabbit.gif", "rocket.gif",
                        "rockinghorse.gif", "shoe.gif", "skateboard.gif", "snail.gif", "squirrel.gif", "sun.gif",
                        "apple.gif", "ball.gif", "bannana.gif", "bear.gif", "bird.gif", "bug.gif",
                        "butterfly.gif", "cake.gif", "cat.gif", "dog.gif", "doll.gif", "dragon.gif", "duck.gif",
                        "elephant.gif", "fish.gif", "flower.gif", "frog.gif", "gift.gif", "hat.gif", "hotdog.gif",
                        "jackinthebox.gif", "keys.gif", "pizza.gif", "plane.gif", "rabbit.gif", "rocket.gif",
                        "rockinghorse.gif", "shoe.gif", "skateboard.gif", "snail.gif", "squirrel.gif", "sun.gif"};
            Container container;
            public GameGUI()

                  container = getContentPane();
                  JPanel southLayout = new JPanel();
                  JPanel northLayout = new JPanel();
                  JPanel border = new JPanel (new BorderLayout ());
                  CloseButtonListener closeButtonListener = new CloseButtonListener();
                  // South Layout
                  southLayout.setLayout (new FlowLayout());
                  startButton = new JButton( "Start New Game");
                  southLayout.add (startButton);
                  closeButton = new JButton( "Exit");
                  southLayout.add (closeButton);
                  // North Layout
                  playerInfo = new JTextArea(5,70);
                  playerInfo.setEditable( false );
                  northLayout.add( new JScrollPane( playerInfo));
                  // Center Layout
                  JPanel imageGrid = new JPanel();
                  imageGrid.setLayout(new GridLayout(8,8,3,3));
                  imageButton = new JButton[64];
                  imageOnButton = new ImageIcon[64];
                  imageNull = new ImageIcon("");      
                  scramble (images);
                  for (int i =0; i < images.length; i++)              
                        imageButton[i] = new JButton(""+i);             // Create the array of buttons.
                        imageButton[i].addActionListener(this);                  // Add the listener for button clicks.
                        imageGrid.add(imageButton[i]);                              // Add the buttons to the panel.
                        imageOnButton[i] = new ImageIcon(images[i]);      // Create the array of imageIcons.
                        String playerName = JOptionPane.showInputDialog("Please Enter the Players Name.");
                        String age = JOptionPane.showInputDialog("Enter the Players Age.");
                        int playerAge = Integer.parseInt(age);
                        int playerScore = 0;
                        // Enter Player into Player Array
                        playerArray [lastPlayer] = new Players ( playerName, playerAge, playerScore );
                        playerInfo.append(playerArray [lastPlayer].toString() + "\n");
                        // Prompt for More Players
                        prompt = JOptionPane.showConfirmDialog(null, "Add another Player?");
                  } while( prompt == JOptionPane.YES_OPTION );
            public void actionPerformed(ActionEvent event)
                  for (int i = 0; i < images.length; i++)
                        if ((event.getSource()== imageButton[i])&& status==1)
                              indexOfFirst = i;
                              status = 2;
                        else if ((event.getSource()== imageButton[i])&& status == 2)
                        System.out.println(" "+i+" "+images[i]+" "+indexOfFirst+" "+
                                    JOptionPane.showMessageDialog(null,"Match\nSelect Again");
                                    // Add point to player
                                    JOptionPane.showMessageDialog(null,"Try Again");
                                    // Switch to next player
                                    if (currentTurn == lastPlayer)
                                          currentTurn = 0;
                                          JOptionPane.showMessageDialog(null,"First Player's Turn");
                                          JOptionPane.showMessageDialog(null,"Next Player");
                              status = 1;
            }// End actionPerformed.
            public static void scramble(String array[])
                for (int i = 0; i < array.length; i++)
                   swap(array, (int)(Math.random()* 63), (int)(Math.random()* 63));
            public static void swap(String array[], int firstElement, int secondElement)
                String temp = array[firstElement];
                array[firstElement] = array[secondElement];
                array[secondElement] = temp;
      public static void main(String[] args)
            GameGUI application = new GameGUI();
      }//End main.
    class CloseButtonListener implements ActionListener
         public void actionPerformed(ActionEvent evt)
}// End JFrame.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Hi reefcrazed,

Can you add a class variable to the Player class called score?
Then you would have setScore(), getScore(),
Maybe a clearScore, or just do setScore(0).
That sound reasonable?

Joe P
reefcrazedAuthor Commented:
I actually have that setup in the player class.

I just wasn't sure how I could make that increment up.
reefcrazedAuthor Commented:
hehe btw Hey Bogo. I fixed the points for the last question you helped me with. =)
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

Why thank you, I remember seeing that. =)
You could increment that like so:

Player p = new Player();
p.setScore( (p.getScore() + 1) );

Or, have a CONSTANT class variable (or multiple) for score increments
p.setScore( (p.getScore() + SCORE_INCREMENT) );

There could be multiple score increments, which is why I considered CONSTANTS.

Joe P
reefcrazedAuthor Commented:
Added this line
       thePlayers.setScore( (thePlayers.getScore() + SCORE_INCREMENT) );

When I run the program and get a match it crashed with a null pointer.

Will the score change automatically in the JTextArea or would I need some way to refresh it after I change the score?
1. Make sure that you define SCORE_INCREMENT as a constant in your programm here is the code:
private final int SCORE_INREMENT = 10; // put whatever values you want here, I put 10, a common number

2. You said:
>Will the score change automatically in the JTextArea or would I need some way to refresh it after I change the score?
A JTextArea only changes text when setText() is called.  We did not call setText() yet.  So just add this line, after we set the new score with p.setScore().  I will call the JTextArea txtArea, I don't know your actual name for it but make sure you use the name you gave the textarea in your program:

Joe P
reefcrazedAuthor Commented:
Getting this: " The method setText(String) in the type JTextComponent is not applicable for the arguments (int) "

I set the constant and reconifgured the line to fit my variables.
Manikandan ThiagarajanSenior consultantCommented:
could you give me the player class?
reefcrazedAuthor Commented:
// Players Class
public class Players extends Object

      private String name;
      int age;
      int score;
// Constructor      
public Players ( String playerName,  int playerAge, int playerScore )
      name = playerName;
      age = playerAge;
      score = playerScore;

// Set First Name
public void setName ( String playerName )
      name = playerName;
// return First Name
public String getName ()
            return name;
// Set Last Name
public void setAge ( int playerAge )
      age = playerAge;
// return Last Name
public int getAge ()
            return age;

// Set Genre
public void setScore ( int playerScore )
      score = playerScore;
// return Genre
public int getScore ()
      return score;
// return String representation of Author object
public String toString ()
            return "Player Name: " + getName () + "\tPlayer Age: " + getAge () +
                  "\t\tPlayer Score: " + getScore();
}// End Players class
Mayank SAssociate Director - Product EngineeringCommented:
>> The method setText(String) in the type JTextComponent is not applicable for the arguments (int)

You are passing an integer to it. You need to pass a string:

textField.setText ( Integer.toString ( yourInt ) ) ;

>> public class Players extends Object

extends Object is not required there.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
reefcrazedAuthor Commented:
lol just noticed I forgot to change my comments.
Recycled it from another class i wrote.
That class should be called 'Player' ;-) A collection of them would be 'Players' or 'Team'
> The method setText(String) in the type JTextComponent is not applicable for the arguments (int)
You could do this:

I normally use the second way, its shorter, its sorta a hack to make that a string.
Joe P

Mayank SAssociate Director - Product EngineeringCommented:
I wouldn't recommend the second method :) its a useless string concatenation (which does not even use StringBuffer, so is worse in performance). It might internally anyway end up trying to convert p.getScore () to a String using Integer.toString () for doing the concatenation.
Alrighty.  Use Integer.toString()
Mayank SAssociate Director - Product EngineeringCommented:
Any reason for a B-grade?
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.