Java Guess the Number Game Using Swing with code explanation

In this tutorial, we'll create a “Guess the Number” game in Java using the Swing framework for the graphical user interface (GUI).

The player will attempt to guess a random number within a specified range, and the program will provide feedback after each guess (whether the guess is too high or too low).

The game will continue until the player guesses the correct number.

Features of the Game:

The game generates a random number between 1 and 100.
The player inputs their guess using a text field.
Feedback is provided if the guess is too high, too low, or correct.
The player can reset the game after guessing correctly.

Complete Code of the Game

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class GuessTheNumberGame extends JFrame {
    private JTextField guessField;  // Field where the player enters their guess
    private JButton guessButton, resetButton;  // Buttons for submitting guess and resetting the game
    private JLabel feedbackLabel, attemptLabel;  // Labels for feedback and showing number of attempts
    private int randomNumber;  // Random number to guess
    private int attempts;  // Number of attempts made by the player

    // Constructor to set up the game
    public GuessTheNumberGame() {
        setTitle("Guess The Number Game");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);  // Center the window on the screen

        // Initialize components
        guessField = new JTextField(10);
        guessButton = new JButton("Guess");
        resetButton = new JButton("Reset");
        feedbackLabel = new JLabel("Enter a number between 1 and 100.");
        attemptLabel = new JLabel("Attempts: 0");

        // Set up the layout
        setLayout(new GridLayout(4, 1));
        JPanel inputPanel = new JPanel();  // To hold input field and button
        inputPanel.add(new JLabel("Your Guess: "));
        inputPanel.add(guessField);
        inputPanel.add(guessButton);

        // Add components to the frame
        add(feedbackLabel);
        add(inputPanel);
        add(attemptLabel);
        add(resetButton);

        // Generate the random number to guess
        resetGame();

        // Add action listeners
        guessButton.addActionListener(new GuessButtonListener());
        resetButton.addActionListener(new ResetButtonListener());

        // Make the frame visible
        setVisible(true);
    }

    // Method to reset the game
    private void resetGame() {
        Random rand = new Random();
        randomNumber = rand.nextInt(100) + 1;  // Generate a number between 1 and 100
        attempts = 0;  // Reset the attempt count
        feedbackLabel.setText("Enter a number between 1 and 100.");
        attemptLabel.setText("Attempts: 0");
        guessField.setText("");
    }

    // Inner class for handling the "Guess" button click
    private class GuessButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String guessText = guessField.getText();
            try {
                int guess = Integer.parseInt(guessText);  // Convert the guess to an integer

                attempts++;  // Increment the attempt count
                attemptLabel.setText("Attempts: " + attempts);

                // Check if the guess is too high, too low, or correct
                if (guess < randomNumber) { feedbackLabel.setText("Too low! Try again."); } else if (guess > randomNumber) {
                    feedbackLabel.setText("Too high! Try again.");
                } else {
                    feedbackLabel.setText("Correct! You guessed the number.");
                    JOptionPane.showMessageDialog(null, "Well done! You guessed the number in " + attempts + " attempts.");
                }
            } catch (NumberFormatException ex) {
                feedbackLabel.setText("Invalid input! Please enter a valid number.");
            }
        }
    }

    // Inner class for handling the "Reset" button click
    private class ResetButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            resetGame();  // Reset the game when the reset button is clicked
        }
    }

    // Main method to run the game
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new GuessTheNumberGame());
    }
}

Explanation of the Code

1. Import Statements

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
javax.swing.*: Imports all the Swing components used to create the GUI (e.g., JFrame, JButton, JTextField, JLabel, etc.).
java.awt.*: Imports layout managers and basic graphical classes.
java.awt.event.*: Imports event listener classes for handling button clicks.
java.util.Random: Allows us to generate random numbers.

2. Class Declaration and Instance Variables

public class GuessTheNumberGame extends JFrame {
    private JTextField guessField;
    private JButton guessButton, resetButton;
    private JLabel feedbackLabel, attemptLabel;
    private int randomNumber;
    private int attempts;
}
JTextField guessField: A text field where the user will input their guess.
JButton guessButton and resetButton: Buttons for submitting guesses and resetting the game.
JLabel feedbackLabel: Provides feedback to the player (e.g., "Too high!", "Correct!").
JLabel attemptLabel: Displays the number of attempts made by the player.
int randomNumber: The randomly generated number that the player must guess.
int attempts: Tracks the number of attempts the player has made.

3. Constructor

public GuessTheNumberGame() {
    setTitle("Guess The Number Game");
    setSize(400, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    guessField = new JTextField(10);
    guessButton = new JButton("Guess");
    resetButton = new JButton("Reset");
    feedbackLabel = new JLabel("Enter a number between 1 and 100.");
    attemptLabel = new JLabel("Attempts: 0");

    setLayout(new GridLayout(4, 1));
    JPanel inputPanel = new JPanel();
    inputPanel.add(new JLabel("Your Guess: "));
    inputPanel.add(guessField);
    inputPanel.add(guessButton);

    add(feedbackLabel);
    add(inputPanel);
    add(attemptLabel);
    add(resetButton);

    resetGame();

    guessButton.addActionListener(new GuessButtonListener());
    resetButton.addActionListener(new ResetButtonListener());

    setVisible(true);
}

Frame Setup:

setTitle(): Sets the title of the window.
setSize(): Sets the window size to 400x200 pixels.
setDefaultCloseOperation(): Ensures the application exits when the window is closed.
setLocationRelativeTo(null): Centers the window on the screen.

Component Setup:

guessField: A text field where the user will enter their guess.
guessButton: The button to submit the guess.
resetButton: The button to reset the game.
feedbackLabel: A label that provides feedback based on the guess.
attemptLabel: A label that tracks the number of attempts.

Layout Setup:

setLayout(new GridLayout(4, 1)): Uses a grid layout with 4 rows and 1 column.
Adds components (label, input panel, attempt label, and reset button) to the frame.

Action Listeners:

guessButton.addActionListener(): Attaches an event listener to handle the "Guess" button click.
resetButton.addActionListener(): Attaches an event listener to handle the "Reset" button click.

Initial Setup:

resetGame(): Initializes the game by generating a random number and resetting the attempt count.

4. resetGame() Method

private void resetGame() {
    Random rand = new Random();
    randomNumber = rand.nextInt(100) + 1;
    attempts = 0;
    feedbackLabel.setText("Enter a number between 1 and 100.");
    attemptLabel.setText("Attempts: 0");
    guessField.setText("");
}
Random rand = new Random(): Creates a Random object.
rand.nextInt(100) + 1: Generates a random number between 1 and 100.

Resets the game state:

attempts = 0: Resets the attempt count.
feedbackLabel.setText(): Resets the feedback message.
attemptLabel.setText(): Resets the attempt count display.
guessField.setText(""): Clears the input field.

5. GuessButtonListener Class

private class GuessButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        String guessText = guessField.getText();
        try {
            int guess = Integer.parseInt(guessText);

            attempts++;
            attemptLabel.setText("Attempts: " + attempts);

            if (guess < randomNumber) { feedbackLabel.setText("Too low! Try again."); } else if (guess > randomNumber) {
                feedbackLabel.setText("Too high! Try again.");
            } else {
                feedbackLabel.setText("Correct! You guessed the number.");
                JOptionPane.showMessageDialog(null, "Well done! You guessed the number in " + attempts + " attempts.");
            }
        } catch (NumberFormatException ex) {
            feedbackLabel.setText("Invalid input! Please enter a valid number.");
        }
    }
}

Handles Guess Input:

Integer.parseInt(guessText): Converts the input text to an integer.
Increments the attempt count and updates the attempt label.
Compares the guess with the random number:
Displays "Too low!" if the guess is less than the random number.
Displays "Too high!" if the guess is greater than the random number.
Displays "Correct!" and shows a message dialog if the guess is correct.

Exception Handling:

If the input is not a valid number, it catches a NumberFormatException and displays an error message.

6. ResetButtonListener Class

private class ResetButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        resetGame();
    }
}

Handles Game Reset:

Calls the resetGame() method to restart the game when the reset button is clicked.

7. main() Method

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> new GuessTheNumberGame());
}
SwingUtilities.invokeLater(): Ensures that the game runs on the Event Dispatch Thread (EDT), which is responsible for handling all Swing GUI updates.
new GuessTheNumberGame(): Creates and launches an instance of the game.

Game Flow

The game generates a random number between 1 and 100.
The player enters a guess in the text field and clicks the “Guess” button.
The program checks if the guess is too high, too low, or correct, and displays appropriate feedback.
If the guess is correct, a congratulatory message is displayed, and the player can click “Reset” to play again.
The player can reset the game at any time using the “Reset” button.

Example Run of the Program

The window opens with the message “Enter a number between 1 and 100.”
The player inputs their guess, e.g., 50, and clicks “Guess.”
If the guess is too high, the feedback will show “Too high! Try again.”
If the guess is too low, the feedback will show “Too low! Try again.”
If the guess is correct, the feedback will show “Correct! You guessed the number.”
The player can click “Reset” to start a new game with a new random number.

Conclusion

By following this tutorial, you've created a fully functional “Guess the Number” game using Java Swing.

This program demonstrates:

Creating a GUI with Swing components (JFrame, JLabel, JButton, JTextField).
Handling user input with text fields and buttons.
Providing real-time feedback in the GUI.
Using Random to generate a random number.
Implementing action listeners to handle button clicks.
You can further enhance this game by adding more features, such as:

Difficulty levels (e.g., allowing the player to choose a range of numbers).
Limiting the number of guesses.
Displaying a history of previous guesses.

Related posts

Java Random Maze Generator Using Swing Tutorial

Java Dice Roll Simulator Using Swing Tutorial

Java Palindrome Checker Using Swing Tutorial