Number Guessing Game in Java Swing with Source Code

Hello Friends, in this tutorial, we will learn how to create a Number Guessing Game in Java Swing with Source Code. In the previous tutorials, we have already learned how to create a Login form in Java Swing and a Calculator application using Java Swing. Now in this tutorial, we will create a GUI Number Guessing Game in Java step by step, and the source code of the project will be given at the end of the tutorial.

In short, What will happen in this GUI Number Guessing Game in Java Swing is the generation of a random number ranging between 0 to 100. The objective for the Player is to guess the correct number. If the Player successfully guesses the right number, a message dialog box will appear to declare their victory. However, if the Player’s guess is incorrect, a hint will be provided indicating whether the guessed number is low or high. This allows the Player to make subsequent guesses.

Additionally, there will be an option to “Give Up” the Game if the Player decides not to continue guessing and wishes to reveal the number. Furthermore, a “New game” option will be available, enabling the Player to start a fresh game.

The bottom section of the Game will feature statistics indicating the number of attempts made by the Player, the highest score achieved, and the time taken by the Player.

Prerequisite

In order to build our GUI Number Guessing Game using Java Swing, it is essential to possess a solid understanding of the basic components of Java Swing. Below, I have listed all the necessary topics that we need to create the Number Guessing Game in Java Swing.

If you have finished covering the topics mentioned earlier, we can proceed with our tutorial on building a Number Guessing Game in Java Swing, including the source code.

Number Guessing Game in Java Swing/ with GUI

Importing Packages

Step 1

  • In the first step, we need to import all the essential packages in our program so that we will be able to use all the interfaces and classes that we will use in our program.

Creating a Class GuessingGame.java

Step 2

  • In this step, we will create a class GuessingGame.java that will implement both ActionListner and KeyListener interface.
  • We will implement the ActionListener and KeyListener interface because we will do some button click events and key-typed events in our program. For this, we have already imported the necessary package in our class, which is java.awt.event.*;.
  • ActionListener contains only one method actionPerformed(ActionEvent e), and KeyListener contains three methods keyPressed(KeyEvent e), keyReleased(KeyEvent e) and keyTyped(KeyEvent e), So if we are implementing these interfaces in our class, then we must have to override their methods into that class.
  • Next, we will create the main method (public static void main(String[] args) of our class.

Creating GUI for Number Guessing Game in Java

Step 3

  • In this step, we will prepare the GUI of our Number Guessing Game.
  • For this, we will create the constructor of our class.
  • Now, create the object of one JFrame and two JPanel.
  • Next, we will set the properties of the JFrame and Jpanel using their objects.
  • Next, we will add the Jpanels to the JFrame.
  • Next, we will create the object of our class inside the main method.
  • Below is the code, and the explanations are given in the comments.
  • Now run your program.
Number Guessing Game in Java Swing with Source Code
Number Guessing Game in Java Swing with Source Code – fig – 1
  • As you can see in the above figure, we have successfully created the GUI for our Number Guessing Game in Java Swing.
  • In the next step, we will add components to it.

Adding Components

Step 4

  • In this step, we will add all the desired components into GUI to create our number guessing game.
  • For this, we will first create the objects of the components and then set some of their properties using their respective methods, and then lastly, we will add them to the container.
  • We will create,
    • 9 JLabel in which,
      • 8 JLabel will be used to display the text, and 1 JLabel will be used to display the image using the ImageIcon class. The image should be within the project folder. I will provide the image with the source code, or you can either choose your particular image as per your requirements.
    • 4 JTextField in which,
      • 1 JTextField will be used to input the guessed number, and the other 3 JTextFields will be used to display the number of attempts made by the player, the highest score, and the time taken by the player, respectively.
      • We will also restrict the character limit of the guessing JTextField to 2 characters using the PlainDocument class so that only two characters can be entered by the player.
    • 4 JButton in which,
      • The first JButton will be used to guess the number, the second JButton will allow the player to give up and reveal the number if they choose not to guess, and the third JButton will be used to start a new game.
  • The code is given below.
  • Now run your program.
Number Guessing Game in Java Swing
Number Guessing Game in Java Swing with Source Code – fig – 2
  • As you can see in the above figure, we have successfully added the components to the container.
  • In the following step, we need to implement the necessary functionalities for our JButtons and JTextField so that when the buttons are clicked and text is entered into the JTextField, corresponding actions are performed.

Adding Event Handling to JButtons and JTextField

Step 5

  • To add event handling to our JButtons and JTextField, we first have to register(add) ActionListener to JButtons and KeyListener to JTextField.
  • For JButtons, we will call the addActionListener() method using the object of the desired component. The parameter of the addActionListener is the object of that class in which the ActionListener interface is implemented, and since we are in the same class so we will pass this as argument.
  • For JTextField, we will call the addKeyListener() method using the object of the desired component. The parameter of the addKeyListener is the object of that class in which the ActionListener interface is implemented, and since we are in the same class so we will pass this as argument.
  • By registering the JButtons, the actionPerformed() will be called whenever we click on any of the registered JButtons.
  • By registering the JTextField to KeyListener, three methods will be called whenever we input any text into the JTextField, which are,
    • keyTyped(KeyEvent e)
    • keyPressed(KeyEvent e)
    • keyReleased(KeyEvent e)
  • Code is given below.

Implementing Game Logic

Step 6

Now we want that,

  • Upon executing the program, a random number within the range between 0 to 100 should be generated. To accomplish this, we will use the Random class in Java.
  • Whenever the player enters the number to be guessed in the JTextField, only numerical input should be permitted, and alphabets or other characters should not be accepted. For this, we will code the desired code inside the keyTyped(KeyEvent e) method.
  • The desired actions that we want in response whenever we click on the Jbuttons will be coded inside the actionPerformed(ActionEvent e) method.
  • Upon clicking the Guess Button,
    • If the guess text field is empty, the message dialog box should be displayed with the message “Invalid Input.” For the message dialog box, we will use the showMessageDialog() method of JOptionPane class.
    • If the guessed number matches the random number generated by the program, a victory message should be displayed in the message dialog box.
    • If the guessed number is low, then the hint should be displayed to the player that “try again this guessed number is low.”
    • If the guessed number is high, then the hint should be displayed to the player that “try again this guessed number is high.”
    • Counter variables will also be created to store the values of attempts made by the player and the highest score of the player.
    • The highest score will be determined based on the following logic: if the player is playing for the first time, it will be equal to the number of attempts made to guess the correct number. However, if the player starts a new game without exiting the program, the highest score will be the lowest number of attempts made across all games to reach the target.
    • The player will also be presented with a timer that begins upon running the program and functions as a stopwatch, showcasing the elapsed time.
  • Upon clicking the Give Up button,
    • The timer should be stopped, and the correct number should be revealed to the player through the message dialog box.
  • Upon clicking the New Game button,
    • A new Game should be opened with timer starting from 0 and the program generating a new random number so the player can guess again.
  • The final code of our project, Number Guessing Game in Java Swing, is given below with explanations in the comments.
  • Now run your program.
Number Guessing Game in Java Swing
Number Guessing Game in Java Swing with Source Code – fig – 3
  • So, we have successfully created our number guessing game in Java with GUI, as you can see in the above animation.

Screenshots of the Number Guessing Game in Java Swing

Number Guessing Game in Java Swing with Source Code – fig – 4

 

Number Guessing Game in Java Swing with Source Code – fig – 5

 

Number Guessing Game in Java Swing with Source Code – fig – 6

 

Number Guessing Game in Java Swing with Source Code – fig – 7

Number Guessing Game in Java Swing with Source Code Download

  • You can download the source code of the number guessing game in Java with GUI by clicking the button below.

Number Guessing Game in Java PDF Download

  • You can download the PDF file of this tutorial by clicking the button below.

Wrapping Up

To wrap up, that was the complete tutorial on creating a Number Guessing Game in Java Swing, along with the source code. If you have any queries or need additional assistance, feel free to ask by commenting on this post. Thank you.


People Are Also Reading…

Leave a Comment