Java Dice Roll Simulator Using Swing Tutorial

In this tutorial, we will build a Dice Roll Simulator in Java using Swing for the graphical user interface (GUI). The app will simulate rolling one or more dice, and it will display random outcomes for each roll.

The app allows users to select the number of dice to roll and shows the result of each roll.

Features:

The user can specify how many dice to roll.
The app simulates random dice rolls and displays the results.
The app uses Swing components like JTextField, JButton, and JLabel for input and output.
The dice results are generated using Java’s Random class to simulate rolling a six-sided die.

Complete Code

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

public class DiceRollSimulatorApp extends JFrame {

    private JTextField numberOfDiceField;  // Input for the number of dice
    private JButton rollButton;            // Button to trigger dice roll
    private JLabel resultLabel;            // Label to display the dice results
    private Random random;                 // Random number generator

    // Constructor to set up the GUI
    public DiceRollSimulatorApp() {
        setTitle("Dice Roll Simulator");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);  // Center the window on the screen

        random = new Random();

        // Create components
        JLabel promptLabel = new JLabel("Enter number of dice to roll:");
        numberOfDiceField = new JTextField(5);
        rollButton = new JButton("Roll Dice");
        resultLabel = new JLabel("Result: ", SwingConstants.CENTER);
        resultLabel.setFont(new Font("Serif", Font.BOLD, 16));

        // Panel for user input
        JPanel inputPanel = new JPanel();
        inputPanel.add(promptLabel);
        inputPanel.add(numberOfDiceField);
        inputPanel.add(rollButton);

        // Set layout for the frame
        setLayout(new BorderLayout());
        add(inputPanel, BorderLayout.NORTH);
        add(resultLabel, BorderLayout.CENTER);

        // Add action listener to the roll button
        rollButton.addActionListener(new RollButtonListener());

        setVisible(true);
    }

    // Method to simulate rolling multiple dice
    private String rollDice(int numberOfDice) {
        StringBuilder result = new StringBuilder("You rolled: ");
        for (int i = 0; i < numberOfDice; i++) {
            int rollResult = random.nextInt(6) + 1;  // Simulate a roll (1 to 6)
            result.append(rollResult);
            if (i < numberOfDice - 1) {
                result.append(", ");  // Add a comma between results
            }
        }
        return result.toString();
    }

    // Action listener for the roll button
    private class RollButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                int numberOfDice = Integer.parseInt(numberOfDiceField.getText());
                if (numberOfDice <= 0) { resultLabel.setText("Please enter a positive number."); } else { String diceResults = rollDice(numberOfDice); resultLabel.setText(diceResults); } } catch (NumberFormatException ex) { resultLabel.setText("Please enter a valid number."); } } } // Main method to run the app public static void main(String[] args) { SwingUtilities.invokeLater(() -> new DiceRollSimulatorApp());
    }
}

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.*: Provides Swing components like JFrame, JButton, JTextField, and JLabel for creating the GUI.
java.awt.*: Provides layout and graphical utilities like BorderLayout, Font, and Dimension.
java.awt.event.*: Provides event listener classes for handling button click events.
java.util.Random: Provides a random number generator to simulate rolling dice.

2. Class Declaration and Instance Variables

public class DiceRollSimulatorApp extends JFrame {
    private JTextField numberOfDiceField;  // Input for the number of dice
    private JButton rollButton;            // Button to trigger dice roll
    private JLabel resultLabel;            // Label to display the dice results
    private Random random;                 // Random number generator
}
JTextField numberOfDiceField: A text field for the user to input how many dice they want to roll.
JButton rollButton: A button that triggers the dice roll simulation.
JLabel resultLabel: A label that displays the results of the dice rolls.
Random random: A random number generator to simulate rolling dice.

3. Constructor

public DiceRollSimulatorApp() {
    setTitle("Dice Roll Simulator");
    setSize(400, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);  // Center the window on the screen

    random = new Random();

    // Create components
    JLabel promptLabel = new JLabel("Enter number of dice to roll:");
    numberOfDiceField = new JTextField(5);
    rollButton = new JButton("Roll Dice");
    resultLabel = new JLabel("Result: ", SwingConstants.CENTER);
    resultLabel.setFont(new Font("Serif", Font.BOLD, 16));

    // Panel for user input
    JPanel inputPanel = new JPanel();
    inputPanel.add(promptLabel);
    inputPanel.add(numberOfDiceField);
    inputPanel.add(rollButton);

    // Set layout for the frame
    setLayout(new BorderLayout());
    add(inputPanel, BorderLayout.NORTH);
    add(resultLabel, BorderLayout.CENTER);

    // Add action listener to the roll button
    rollButton.addActionListener(new RollButtonListener());

    setVisible(true);
}

Frame Setup:

setTitle(“Dice Roll Simulator”): Sets the window title.
setSize(400, 200): Sets the window size to 400×200 pixels.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the program exits when the window is closed.
setLocationRelativeTo(null): Centers the window on the screen.

Component Setup:

numberOfDiceField = new JTextField(5): Creates a text field for the user to input how many dice they want to roll.
rollButton = new JButton(“Roll Dice”): Creates the button that the user clicks to roll the dice.
resultLabel = new JLabel(“Result: “, SwingConstants.CENTER): Creates a label to display the results, with text centered.

Panel Setup:

inputPanel.add(promptLabel): Adds the prompt label to the input panel.
inputPanel.add(numberOfDiceField): Adds the text field to the input panel.
inputPanel.add(rollButton): Adds the roll button to the input panel.

Layout Setup:

setLayout(new BorderLayout()): Uses a BorderLayout to position components.
add(inputPanel, BorderLayout.NORTH): Adds the input panel to the top of the window.
add(resultLabel, BorderLayout.CENTER): Adds the result label to the center of the window.

4. rollDice() Method

private String rollDice(int numberOfDice) {
    StringBuilder result = new StringBuilder("You rolled: ");
    for (int i = 0; i < numberOfDice; i++) {
        int rollResult = random.nextInt(6) + 1;  // Simulate a roll (1 to 6)
        result.append(rollResult);
        if (i < numberOfDice - 1) {
            result.append(", ");  // Add a comma between results
        }
    }
    return result.toString();
}

Simulating Dice Rolls:
random.nextInt(6) + 1: Generates a random number between 1 and 6 (simulating a roll of a six-sided die).
StringBuilder result = new StringBuilder(): Used to build the result string with the outcome of each dice roll.
The method appends each dice result to the result string and returns the final outcome.

5. Action Listener for the Roll Button

private class RollButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            int numberOfDice = Integer.parseInt(numberOfDiceField.getText());
            if (numberOfDice <= 0) {
                resultLabel.setText("Please enter a positive number.");
            } else {
                String diceResults = rollDice(numberOfDice);
                resultLabel.setText(diceResults);
            }
        } catch (NumberFormatException ex) {
            resultLabel.setText("Please enter a valid number.");
        }
    }
}

Handling Button Clicks:

numberOfDice = Integer.parseInt(numberOfDiceField.getText()): Retrieves the number of dice from the input field.

Input Validation:

If the number of dice is less than or equal to 0, an error message is displayed.
If the input is invalid (non-numeric), an error message is displayed.
rollDice(numberOfDice): Calls the method to simulate rolling the dice and displays the results in the resultLabel.

6. Main Method

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> new DiceRollSimulatorApp());
}

SwingUtilities.invokeLater(): Ensures that the GUI is created and updated on the Event Dispatch Thread (EDT), which is necessary for Swing applications.
new DiceRollSimulatorApp(): Creates and launches the dice roll simulator app.

Customization Ideas

1. Change the Number of Sides on the Dice

Add a dropdown to allow users to select the number of sides on the dice (e.g., 6-sided, 10-sided, or 20-sided dice).

2. Add Dice Images

Add images of dice to visually display the result of each roll instead of just numbers.

3. Improve the User Interface

Enhance the UI by adding colors, better fonts, and tooltips for usability.

4. Display Sum of Rolls

Add an additional label to display the sum of all dice rolled.

Conclusion

This Dice Roll Simulator in Java using Swing allows users to simulate rolling one or more dice, and it demonstrates:

Using Swing components (JFrame, JButton, JTextField, JLabel) to create a graphical user interface.
Generating random numbers to simulate rolling dice.
Handling input validation and providing real-time feedback
.
You can extend this project with more features to suit your needs and make it more interactive!

Related posts

Java Random Maze Generator Using Swing Tutorial

Java Palindrome Checker Using Swing Tutorial

Java Color Picker Tool Using Swing Tutorial