Hi all -

This is my first time posting here, but I'm hoping someone can help me. My homework assignment is to make a GUI number guessing game with the number of guesses shown. I've gotten the entire program working, but for the life of me I can't seem to figure out how to add the section that shows the Number of Guess and how many have been taken so far. If someone could please help me I would be grateful!

Here's my code:
Constructor Section:

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;


public class GuessTheNumber extends JFrame
{
    private int GuessOld = 0;   
    private int number; // application's number
    private JTextField guessInputJTextField; // user input field
    private JLabel prompt1JLabel; // first line of instruction
    private JLabel prompt2JLabel; // second line of instructions
    private JLabel messageJLabel; // displays message of game status
	 private JLabel message2JLabel; //display number of guesses
	 private JLabel random1;
    private JButton newGameJButton; // creates new game
    private Color background; // background color of application

        // set up GUI and initialize values
        public GuessTheNumber()
        {
            super( "Guessing Game" );


                setLayout(new FlowLayout());
                background = Color.LIGHT_GRAY; // set background to light gray

                prompt1JLabel = new JLabel( "I have a number between 1 and 1000." ); // describe game
                add(prompt1JLabel);
                prompt2JLabel = new JLabel( "Can you guess my number? Enter your Guess:" ); // prompt user
                add(prompt2JLabel);

                guessInputJTextField = new JTextField( 5 ); // to enter guesses
                guessInputJTextField.addActionListener( new GuessHandler( ) );
                add(guessInputJTextField);
       
                messageJLabel = new JLabel( "" );
                add(messageJLabel);


                newGameJButton = new JButton( "New Game" ); // create "New Game" button
                add ( newGameJButton ); // add newGame button to JFrame
               
                Random generator = new Random();
                number = generator.nextInt(1001);//create random number
					
                newGameJButton.addActionListener(

                        new ActionListener() // anonymous inner class
                        {
                        public void actionPerformed( ActionEvent e )
                        {
                                               
                            guessInputJTextField.setText("");
                            Random generator = new Random();
          						 int number = generator.nextInt(1001);
									 random1.setText("" + number );
									 SwingUtilities.updateComponentTreeUI(random1);                  
									 messageJLabel.setText("");
                            guessInputJTextField.setEditable(true);


                           
                           
                        } // end method actionPerformed
                        } // end anonymous inner class
                        ); // end call to addActionListener
               
   
                theGame(); // start new game
                } // end GuessGameFrame constructor

       

               

            // choose a new random number
        public void theGame()
        {
   
        } // end method theGame

        // change background color
    
   		class GuessHandler implements ActionListener{    
		   public void actionPerformed( ActionEvent e )
            {
               
				int Guess;
			
               
               Guess = Integer.parseInt(guessInputJTextField.getText());
               
              if ( Math.abs( number - Guess ) < Math.abs( number - GuessOld) ){
                // Hotter
                getContentPane().setBackground(Color.RED);
            }
            else{
                                   
                // Colder
                getContentPane().setBackground(Color.BLUE);
            }
                GuessOld = Guess;
                if ( Guess > number )
                {
                    messageJLabel.setText( "Too High." );
                    SwingUtilities.updateComponentTreeUI(messageJLabel);
                }
               
                if( Guess < number )
                    {
                                   
                        messageJLabel.setText( "Too Low." );
                        SwingUtilities.updateComponentTreeUI(messageJLabel);
                   
                }
				
					  // end if
                   
                       
               
                if ( Guess == number ) // guess is too low
                        {
                            messageJLabel.setText( "Correct!" );
                            SwingUtilities.updateComponentTreeUI(messageJLabel);
                            guessInputJTextField.setEditable(false);
                           
                               
                               

                        }
                           
                   
                   
                }

            }
}

Part that makes program run:

import javax.swing.JFrame;

public class GameGuessTheNumber{
	public static void main(String args[]) throws Exception{
		GuessTheNumber game = new GuessTheNumber();
		game.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		game.setSize(550, 150);
		game.setVisible(true);
		}
	}

Again, any help given would be greatly appreciated!

Thanks,
Kat

VernonDozier commented: Code tags on first post. +16

Recommended Answers

All 7 Replies

private JLabel message2JLabel; //display number of guesses

You do nothing with this JLabel , so there's no sense having it. I see no variable named numGuesses or anything similar. You need one. Initialize it to 0 in your constructor, then instantiate message2Label in your constructor and set it to "0" and add it to your JFrame. In your GuessHandler /ActionListener, increment the number of guesses and update your message2Label to reflect the new number of guesses.

Okay, that makes sense. One little problem (and it's probably my stupidity.) I have no idea where to put the message2JLabel. My code is below as it has been edited.
Constructor portion

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;


public class GuessTheNumber extends JFrame
{
  	 private int Guesses = 0;  
	 private int GuessOld = 0;   
    private int number; // application's number
    private JTextField guessInputJTextField; // user input field
    private JLabel prompt1JLabel; // first line of instruction
    private JLabel prompt2JLabel; // second line of instructions
    private JLabel messageJLabel; // displays message of game status
	 private JLabel message2JLabel; //display number of guesses
	 private JLabel random1 = new JLabel("");
    private JButton newGameJButton; // creates new game
    private Color background; // background color of application

        // set up GUI and initialize values
        public GuessTheNumber()
        {
            super( "Guessing Game" );


                setLayout(new FlowLayout());
                background = Color.LIGHT_GRAY; // set background to light gray

                prompt1JLabel = new JLabel( "I have a number between 1 and 1000." ); // describe game
                add(prompt1JLabel);
                prompt2JLabel = new JLabel( "Can you guess my number? Enter your Guess:" ); // prompt user
                add(prompt2JLabel);

                guessInputJTextField = new JTextField( 5 ); // to enter guesses
                guessInputJTextField.addActionListener( new GuessHandler( ) );
                add(guessInputJTextField);
       
                messageJLabel = new JLabel( "" );
                add(messageJLabel);


                newGameJButton = new JButton( "New Game" ); // create "New Game" button
                add ( newGameJButton ); // add newGame button to JFrame
               
                Random generator = new Random();
                number = generator.nextInt(1001);//create random number
					
                newGameJButton.addActionListener(

                        new ActionListener() // anonymous inner class
                        {
                        public void actionPerformed( ActionEvent e )
                        {
                                               
                            guessInputJTextField.setText("");
                            Random generator = new Random();
          						 int number = generator.nextInt(1001);
									 random1.setText("" + number );
									 SwingUtilities.updateComponentTreeUI(random1);                  
									 messageJLabel.setText("");
                            guessInputJTextField.setEditable(true);
									 Guesses++;
						

                           
                           
                        } // end method actionPerformed
                        } // end anonymous inner class
                        ); // end call to addActionListener
               
   
                theGame(); // start new game
                } // end GuessGameFrame constructor

       

               

            // choose a new random number
        public void theGame()
        {
   
        } // end method theGame

        // change background color
    
   		class GuessHandler implements ActionListener{    
		   public void actionPerformed( ActionEvent e )
            {
               
				int Guess;
			
               
               Guess = Integer.parseInt(guessInputJTextField.getText());
		      if ( Math.abs( number - Guess ) < Math.abs( number - GuessOld) ){
                // Hotter
                getContentPane().setBackground(Color.RED);

            }
            else{
                                   
                // Colder
                getContentPane().setBackground(Color.BLUE);
            }
                GuessOld = Guess;
                if ( Guess > number )
                {
                    messageJLabel.setText( "Too High." );
                    SwingUtilities.updateComponentTreeUI(messageJLabel);
  
					 }
            
                if( Guess < number )
                    {
                                   
                        messageJLabel.setText( "Too Low." );
                        SwingUtilities.updateComponentTreeUI(messageJLabel);
                   
                }
				
					  // end if
                   
                       
               
                if ( Guess == number ) // guess is too low
                        {
                            messageJLabel.setText( "Correct!" );
                            SwingUtilities.updateComponentTreeUI(messageJLabel);
                            guessInputJTextField.setEditable(false);
                           
                               
                               

                        }
                           
                   
                   
                }

            }
}

Program portion

import javax.swing.JFrame;

public class GameGuessTheNumber{
	public static void main(String args[]) throws Exception{
		GuessTheNumber game = new GuessTheNumber();
		game.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		game.setSize(550, 150);
		game.setVisible(true);
		}
	}

This parts not included after I deleted when it didn't work.

I tried adding it to the action listener and obviously that didn't work out, but if it is supposed to go into the last part I have no idea where in the if-else-if statement I should put it.

Thanks for your help!

Kat

You added it to the wrong ActionListener (you added it to the "New Game" button's ActionListener, not the JTextrField's ActionListener. Add the label in the constructor, where you added the other labels. I formatted your code so it's easier to follow, added a couple of lines, and moved a line or two.

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;

public class GuessTheNumber extends JFrame
{
    private int Guesses = 0;
    private int GuessOld = 0;
    private int number; // application's number
    private JTextField guessInputJTextField; // user input field
    private JLabel prompt1JLabel; // first line of instruction
    private JLabel prompt2JLabel; // second line of instructions
    private JLabel messageJLabel; // displays message of game status
    private JLabel message2JLabel; //display number of guesses
    private JLabel random1 = new JLabel("");
    private JButton newGameJButton; // creates new game
    private Color background; // background color of application

    // set up GUI and initialize values
    public GuessTheNumber()
    {
        super("Guessing Game");

        setLayout(new FlowLayout());
        background = Color.LIGHT_GRAY; // set background to light gray

        prompt1JLabel = new JLabel("I have a number between 1 and 1000."); // describe game
        add(prompt1JLabel);
        prompt2JLabel = new JLabel("Can you guess my number? Enter your Guess:"); // prompt user
        add(prompt2JLabel);

        guessInputJTextField = new JTextField(5); // to enter guesses
        guessInputJTextField.addActionListener(new GuessHandler());
        add(guessInputJTextField);

        messageJLabel = new JLabel("");
        add(messageJLabel);

        message2JLabel = new JLabel ("");
        add (message2JLabel);

        newGameJButton = new JButton("New Game"); // create "New Game" button
        add(newGameJButton); // add newGame button to JFrame

        Random generator = new Random();
        number = generator.nextInt(1001);//create random number

        newGameJButton.addActionListener(
                new ActionListener() // anonymous inner class
                {
                    public void actionPerformed(ActionEvent e)
                    {
                        guessInputJTextField.setText("");
                        Random generator = new Random();
                        int number = generator.nextInt(1001);
                        random1.setText("" + number);
                        SwingUtilities.updateComponentTreeUI(random1);
                        messageJLabel.setText("");
                        guessInputJTextField.setEditable(true);
                    } // end method actionPerformed
                } // end anonymous inner class
                ); // end call to addActionListener


        theGame(); // start new game
    } // end GuessGameFrame constructor

    // choose a new random number
    public void theGame()
    {
        Guesses = 0;
        message2JLabel.setText(" # of guesses = " + Integer.toString(Guesses));
    } // end method theGame

    // change background color
    class GuessHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            int Guess;

            Guess = Integer.parseInt(guessInputJTextField.getText());
            if (Math.abs(number - Guess) < Math.abs(number - GuessOld))
            {
                // Hotter
                getContentPane().setBackground(Color.RED);
            }
            else
            {
                // Colder
                getContentPane().setBackground(Color.BLUE);
            }

            GuessOld = Guess;
            if (Guess > number)
            {
                messageJLabel.setText("Too High.");
                SwingUtilities.updateComponentTreeUI(messageJLabel);
            }

            if (Guess < number)
            {
                messageJLabel.setText("Too Low.");
                SwingUtilities.updateComponentTreeUI(messageJLabel);
            }
            // end if

            if (Guess == number) // guess is too low
            {
                messageJLabel.setText("Correct!");
                SwingUtilities.updateComponentTreeUI(messageJLabel);
                guessInputJTextField.setEditable(false);
            }

            Guesses++;
            message2JLabel.setText(" # of guesses = " + Integer.toString(Guesses));
        }
    }
}

Lines 51 - 52 - # of guesses label instantiated and added to frame.
Lines 127 - 128 - Guesses incremented and guess label adjusted.
Lines 83 - 84 - I assume this function is called at the start of every new game. Guesses initialized to 0, guess label adjusted.

I recommend possibly taking everything out of lines 65 - 71 and putting it in theGame (), then replace lines 65 - 71 with a call to theGame () . Consider renaming theGame () to newGame () or something more descriptive.

Thank you so much for your help!
The only problem I had when I added your parts to it is that the number of guesses doesn't seem to reset.
Maybe something else in my code is wrong, I'm not sure, but I even tried copying and pasting your code exactly to make sure and it still won't initialize.
Do I need to put a figurative reset button somewhere?
Kind of like the random generator = new Random section?

Thanks again! I really appreciate everything. After other threads that wouldn't reply it has been a relief to find one that gives a reply more than once a day. Thanks so much!

Kat

I thought I'd let you know that I figured out that due to the fact that I was leaving everything in the ActionListener, I needed to move the number of guesses portion there too.
Thank you so much for your help. It did me a world of good and still made me have to figure it out on my own a little bit.

Thanks again,
Kat

commented: What a refreshing change. I wish more people who came here for help were like you. +10

Thank you so much for your help!
The only problem I had when I added your parts to it is that the number of guesses doesn't seem to reset.
Maybe something else in my code is wrong, I'm not sure, but I even tried copying and pasting your code exactly to make sure and it still won't initialize.
Do I need to put a figurative reset button somewhere?
Kind of like the random generator = new Random section?

Thanks again! I really appreciate everything. After other threads that wouldn't reply it has been a relief to find one that gives a reply more than once a day. Thanks so much!

Kat

You're welcome. My code that I posted DOES NOT reset the number of guesses after each game. That's one of the reasons I offered the advice I did regarding putting lines 65 - 71 (there's nothing in these lines that resets Guesses to 0) in theGame () and then calling theGame () from your ActionListener. In other words, change this:

newGameJButton.addActionListener(
                new ActionListener() // anonymous inner class
                {
                    public void actionPerformed(ActionEvent e)
                    {
                        guessInputJTextField.setText("");
                        Random generator = new Random();
                        int number = generator.nextInt(1001);
                        random1.setText("" + number);
                        SwingUtilities.updateComponentTreeUI(random1);
                        messageJLabel.setText("");
                        guessInputJTextField.setEditable(true);
                    } // end method actionPerformed
                } // end anonymous inner class
                ); // end call to addActionListener

to this:

newGameJButton.addActionListener(
                new ActionListener() // anonymous inner class
                {
                    public void actionPerformed(ActionEvent e)
                    {
                        theGame ();
                    } // end method actionPerformed
                } // end anonymous inner class
                ); // end call to addActionListener

and this:

// choose a new random number
    public void theGame()
    {
        Guesses = 0;
        message2JLabel.setText(" # of guesses = " + Integer.toString(Guesses));
    } // end method theGame

to this:

// choose a new random number
    public void theGame()
    {
        guessInputJTextField.setText("");
        Random generator = new Random();
        int number = generator.nextInt(1001);
        random1.setText("" + number);
        SwingUtilities.updateComponentTreeUI(random1);
        messageJLabel.setText("");
        guessInputJTextField.setEditable(true);
        Guesses = 0;
        message2JLabel.setText(" # of guesses = " + Integer.toString(Guesses));
    } // end method theGame

On a final note, in red above, I highlighted the word "int". This creates a NEW local variable called number . This variable as nothing to do with your class variable called number (line 21 in my past post). I assume you want that line to refer to your class variable (line 21). If so, get rid of the word "int" in red above. This may have an effect on whether you have the same "correct" number for every game.

I thought I'd let you know that I figured out that due to the fact that I was leaving everything in the ActionListener, I needed to move the number of guesses portion there too.
Thank you so much for your help. It did me a world of good and still made me have to figure it out on my own a little bit.

Thanks again,
Kat

Ah, I was posting as you were. Glad you figured it out. Read my last post regarding local versus class variables too, unless you've solved that one too. I try to leave something for the OP to solve, but I have to log off and that local versus class issue can be really frustrating, so I figured I'd post it now. Glad it worked out for you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.