Java Lottery Number Generator Tutorial with code explanation

In this tutorial, we will build a simple Lottery Number Generator in Java.

The program will generate a set of unique random lottery numbers, which the user can use for games like the lottery or similar random-number-based events.

Here is an image of what you will create

Features of the Lottery Number Generator:

The app will generate a set of 6 unique random numbers between 1 and 49 (commonly used in many lotteries).
The numbers will be displayed in ascending order for better readability.
The user can click a button to generate a new set of random numbers.
The app will use Swing for the GUI, allowing the user to interact with the program easily.

Complete Code

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

public class LotteryNumberGenerator extends JFrame {

    private JLabel numbersLabel;
    private JButton generateButton;

    // Constructor to set up the GUI
    public LotteryNumberGenerator() {
        setTitle("Lottery Number Generator");
        setSize(500, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);  // Center the window on the screen

        // Label to display lottery numbers
        numbersLabel = new JLabel("Lottery Numbers: ", SwingConstants.CENTER);
        numbersLabel.setFont(new Font("Serif", Font.BOLD, 24));

        // Button to generate numbers
        generateButton = new JButton("Generate Numbers");
        generateButton.addActionListener(new GenerateButtonListener());

        // Set up the layout of the app
        setLayout(new BorderLayout());
        add(numbersLabel, BorderLayout.CENTER);
        add(generateButton, BorderLayout.SOUTH);

        setVisible(true);
    }

    // Method to generate 6 unique random numbers between 1 and 49
    private int[] generateLotteryNumbers() {
        Random random = new Random();
        Set numberSet = new HashSet<>();

        // Ensure we get exactly 6 unique numbers
        while (numberSet.size() < 6) { int number = random.nextInt(49) + 1; // Generates numbers from 1 to 49 numberSet.add(number); } // Convert the set to an array and sort it int[] lotteryNumbers = numberSet.stream().mapToInt(Integer::intValue).toArray(); Arrays.sort(lotteryNumbers); return lotteryNumbers; } // Action listener for the generate button private class GenerateButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int[] lotteryNumbers = generateLotteryNumbers(); // Generate numbers numbersLabel.setText("Lottery Numbers: " + Arrays.toString(lotteryNumbers)); // Display numbers } } // Main method to run the app public static void main(String[] args) { SwingUtilities.invokeLater(() -> new LotteryNumberGenerator());
    }
}

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.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
javax.swing.*: Provides the necessary classes to create a graphical user interface (e.g., JFrame, JButton, JLabel).
java.awt.*: Provides layout managers and other graphical utilities (e.g., BorderLayout, Font).
java.awt.event.*: Provides event handling, such as responding to button clicks (ActionEvent, ActionListener).
java.util.*: Provides utilities for generating random numbers (Random), working with collections (Set, HashSet), and sorting (Arrays).

2. Class Declaration and Instance Variables

public class LotteryNumberGenerator extends JFrame {
    private JLabel numbersLabel;
    private JButton generateButton;
}
JLabel numbersLabel: A label to display the generated lottery numbers.
JButton generateButton: A button that the user clicks to generate a new set of random numbers.

3. Constructor

public LotteryNumberGenerator() {
    setTitle("Lottery Number Generator");
    setSize(500, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);  // Center the window on the screen

    numbersLabel = new JLabel("Lottery Numbers: ", SwingConstants.CENTER);
    numbersLabel.setFont(new Font("Serif", Font.BOLD, 24));

    generateButton = new JButton("Generate Numbers");
    generateButton.addActionListener(new GenerateButtonListener());

    setLayout(new BorderLayout());
    add(numbersLabel, BorderLayout.CENTER);
    add(generateButton, BorderLayout.SOUTH);

    setVisible(true);
}

Frame Setup:

setTitle(“Lottery Number Generator”): Sets the window title.
setSize(400, 200): Sets the size of the window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the application exits when the window is closed.
setLocationRelativeTo(null): Centers the window on the screen.

Label Setup:

numbersLabel = new JLabel(“Lottery Numbers: “, SwingConstants.CENTER): A label to display the generated lottery numbers.
setFont(new Font(“Serif”, Font.BOLD, 24)): Sets the font style and size for the label text.

Button Setup:

generateButton = new JButton(“Generate Numbers”): A button to generate lottery numbers.
generateButton.addActionListener(new GenerateButtonListener()): Adds an action listener to handle button clicks.

Layout Setup:

setLayout(new BorderLayout()): Uses a BorderLayout to position components.
add(numbersLabel, BorderLayout.CENTER): Adds the label to the center of the window.
add(generateButton, BorderLayout.SOUTH): Adds the button at the bottom of the window.

Visibility:

setVisible(true): Makes the window visible.

4. generateLotteryNumbers() Method

private int[] generateLotteryNumbers() {
    Random random = new Random();
    Set numberSet = new HashSet<>();

    while (numberSet.size() < 6) {
        int number = random.nextInt(49) + 1;  // Generates numbers from 1 to 49
        numberSet.add(number);
    }

    int[] lotteryNumbers = numberSet.stream().mapToInt(Integer::intValue).toArray();
    Arrays.sort(lotteryNumbers);
    return lotteryNumbers;
}

Random Number Generation:

Random random = new Random(): Creates a Random object to generate random numbers.
random.nextInt(49) + 1: Generates a random number between 1 and 49.
Set numberSet = new HashSet<>(): A set is used to store the numbers, ensuring that all numbers are unique.

Ensuring 6 Unique Numbers:

The while loop ensures that exactly 6 unique numbers are generated.

Convert Set to Array:

numberSet.stream().mapToInt(Integer::intValue).toArray(): Converts the set of numbers into an array.
Arrays.sort(lotteryNumbers): Sorts the numbers in ascending order for better readability.

Return the Lottery Numbers:

The method returns an array of 6 unique, sorted lottery numbers.

5. GenerateButtonListener Class

private class GenerateButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        int[] lotteryNumbers = generateLotteryNumbers();  // Generate numbers
        numbersLabel.setText("Lottery Numbers: " + Arrays.toString(lotteryNumbers));  // Display numbers
    }
}

Button Click Handling:

generateLotteryNumbers(): Calls the method to generate random lottery numbers.
numbersLabel.setText(): Updates the label to display the generated numbers.

6. Main Method

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> new LotteryNumberGenerator());
}
SwingUtilities.invokeLater(): Ensures that the GUI is created and updated on the Event Dispatch Thread (EDT), which is necessary for Swing applications.
new LotteryNumberGenerator(): Creates and launches an instance of the lottery number generator app.

Customization Ideas

1. Change the Range of Numbers

You can change the range of numbers by modifying the value inside the random.nextInt() function. For example, to generate numbers between 1 and 100:

int number = random.nextInt(100) + 1;

2. Change the Number of Lottery Numbers

If you want to generate a different number of lottery numbers (e.g., 5 numbers instead of 6), modify the while loop condition:

while (numberSet.size() < 5) {
    // Generate numbers
}

3. Allow the User to Customize the Number Range

You can add input fields to allow the user to specify the number range and the number of lottery numbers to generate. This can be done by adding JTextField components for user input.

4. Add an Option to Save the Generated Numbers

You can add functionality to save the generated numbers to a file using FileWriter or PrintWriter. This will allow the user to keep a record of their generated numbers.

5. Style the App

You can enhance the appearance of the app by changing the background color, font size, or adding custom icons to the buttons and labels.

Conclusion

This simple Lottery Number Generator demonstrates how to create a Java GUI application using Swing. The app generates random numbers for lottery-style games, ensuring that the numbers are unique and sorted for better readability.

Key concepts covered:

Creating a GUI using Swing (JFrame, JLabel, JButton).
Random number generation using the Random class.
Handling button click events with ActionListener.
Displaying dynamically updated content in a JLabel.

You can expand this project by adding more features like allowing the user to customize the number range or save their results.

Related posts

Java Random Maze Generator Using Swing Tutorial

Java Dice Roll Simulator Using Swing Tutorial

Java Palindrome Checker Using Swing Tutorial