Java: Example - Rolling Dice

This simple program rolls two dice. It is divided into three source files.

  • RollDice.java is both an application (it defines main()) and an applet (it subclasses JApplet).
  • RollDicePanel.java is a subclass of JPanel that creates the GUI interface.
  • Die.java defines a component as a subclass of JPanel, and provides a graphical view of the die face. It implements logic with a roll() method that randomly "rolls" the die.

RollDice.java - the main program / applet

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
// File:   roll_dice2/RollDicePanel.java
// Description: Main program and applet display two dice and roll them.
// Author: Fred Swartz
// Date:   2005-01-29

package roll_dice2;

import java.awt.*;
import javax.swing.*;

///////////////////////////////////////////////////////// class RollDice
/** RollDice.java -- Program to display two dice and roll them.
 * @author Fred Swartz
 * @version 2005-01-29
 * This can run as an application because it has a main method.
 * It can also be used as an applet because it extends JApplet.
 * Use the following for an applet tag. <br>
 * &lt;applet code="roll_dice2.RollDice.class" archive="roll_dice2.jar" 
 *            width="130" height="107"&gt;&lt;/appletgt;
*/
public class RollDice extends JApplet {
    
    //=============================================== applet constructor
    /** Applet constructor requires putting the panel in applet.*/
    public RollDice() {
        this.setContentPane(new RollDicePanel());
    }
    
    //====================================================== method main
    /** Create JFrame and set content pane to a RollDicePanel. */
    public static void main(String[] args) {
        JFrame window = new JFrame("Dice Demo");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setContentPane(new RollDicePanel());
        window.pack();
        window.setVisible(true);
    }//end main
    
}

RollDicePanel.java provides the GUI to this demo program

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
// File:   roll_dice2/RollDicePanel.java
// Description: Panel of GUI, shows button and two dice.
// Author: Fred Swartz
// Date:   2005-01-29

package roll_dice2;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

///////////////////////////////////////////////////////// class RollDicePanel
/** RollDicePanel.java - Panel builds GUI for RollDice application/applet.
    It subclasses JPanel to contain two dice and a button to roll them.

    @author Fred Swartz
    @version 2005-01-29
*/
public class RollDicePanel extends JPanel {
    //=============================================== instance variables
    private Die myLeftDie;     // component for one die 
    private Die myRightDie;

    //====================================================== constructor
    /** Create border layout panel with one button and two dice. */
    RollDicePanel() {
        //... Create the dice
        myLeftDie  = new Die();
        myRightDie = new Die();
        
        //...Create the button to roll the dice
        JButton rollButton = new JButton("New Roll");
        rollButton.setFont(new Font("Sansserif", Font.PLAIN, 24));
        
        //... Add listener.
        rollButton.addActionListener(new RollListener());
        
        //... Layout components
        this.setLayout(new BorderLayout(5, 5));
        this.add(rollButton, BorderLayout.NORTH);
        this.add(myLeftDie , BorderLayout.WEST);
        this.add(myRightDie, BorderLayout.EAST);
    }//end constructor
    
    
    /////////////////////////////////// inner listener class RollListener
    /** Inner listener class for Roll button. */
    private class RollListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            myLeftDie.roll();
            myRightDie.roll();
        }
    }
}

Die.java implements the graphics and logic of a die

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
 72 
 73 
 74 
 75 
 76 
 77 
 78 
 79 
 80 
 81 
 82 
 83 
 84 
 85 
 86 
 87 
 88 
 89 
 90 
 91 
 92 
 93 
 94 
 95 
 96 
 97 
 98 
 99 
100 
101 
102 
103 
104 
105 
// File:   roll_dice2/Die.java
// Description: Models / displays one die.
// Author: Fred Swartz
// Date:   2005-01-29

package roll_dice2;

import java.awt.*;
import javax.swing.*;

////////////////////////////////////////////////////////////// class Die
/** Die.java - Component to display one die (dice).  This class
    subclasses JPanel to display the face, and it provides functions
    to "roll", giving different random values. 
    Possible improvements:
    <ul>
    <li>Use Graphics2 anti-aliasing to smooth the dot edges.</li>
    <li>Add a border.</li>
    </ul>
  @author Fred Swartz
  @version 2003-04-30
*/
public class Die extends JPanel {
    //================================================ constant
    private static final int SPOT_DIAMETER = 9;  // Diameter of spots
    
    //=============================================== instance variables
    private int myFaceValue;     // value that shows on face of die
    //end instance variables
    
    //====================================================== constructor
    /** Initialize to white background and 60x60 pixels. Initial roll.*/
    public Die() {
        setBackground(Color.white);
        //-- Preferred size is set, but layout may change it.
        setPreferredSize(new Dimension(60,60));
        roll();  // Set to random initial value        
    }//end constructor
    
    //====================================================== method roll
    /** Produce random roll in range 1-6.  Causes repaint().
        @return Result of roll (1-6).
    */
    public int roll() {
        int val = (int)(6*Math.random() + 1);   // Range 1-6
        setValue(val);
        return val;
    }//end roll

    //================================================== method getValue
    /** Returns result of last roll.*/
    public int getValue() {
        return myFaceValue;
    }//end setValue

    //================================================== method setValue
    /** Sets the value of the Die.  Causes repaint().
        @param spots Number from 1-6.
    */
    public void setValue(int spots) {
        myFaceValue = spots;
        repaint();    // Value has changed, must repaint
    }//end setValue

    //============================================ method paintComponent
    /** Draws spots of die face. */
    public void paintComponent(Graphics g) {
        super.paintComponent(g);  // Required
        
        int w = getWidth();  // Panel height and width
        int h = getHeight(); 
        
        g.drawRect(0, 0, w-1, h-1);  // Draw border
        
        switch (myFaceValue) {
            case 1: drawSpot(g, w/2, h/2);
                    break;
            case 3: drawSpot(g, w/2, h/2);
                    // Fall thru to next case
            case 2: drawSpot(g, w/4, h/4);
                    drawSpot(g, 3*w/4, 3*h/4);
                    break;
            case 5: drawSpot(g, w/2, h/2);
                    // Fall thru to next case  
            case 4: drawSpot(g, w/4, h/4);
                    drawSpot(g, 3*w/4, 3*h/4);
                    drawSpot(g, 3*w/4, h/4);
                    drawSpot(g, w/4, 3*h/4);
                    break;
            case 6: drawSpot(g, w/4, h/4);
                    drawSpot(g, 3*w/4, 3*h/4);
                    drawSpot(g, 3*w/4, h/4);
                    drawSpot(g, w/4, 3*h/4);
                    drawSpot(g, w/4, h/2);
                    drawSpot(g, 3*w/4, h/2);
                    break;
        }
    }//end paintComponent
    
    /** Utility method used by paintComponent(). */
    //================================================== method drawSpot
    private void drawSpot(Graphics g, int x, int y) {
        g.fillOval(x-SPOT_DIAMETER/2, y-SPOT_DIAMETER/2, SPOT_DIAMETER, SPOT_DIAMETER);
    }
}