Pair of Dice


 

 

Complete Source Code

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


public class PairOfDice {


   public static class PairOfDicePanel extends JPanel {

      int v1 = 1;
      int v2 = 1;

      public void drawDie(Graphics g, int value, int x, int y) {

         g.setColor(Color.WHITE);
         g.fillRect(x,y,100,100);
         g.setColor(Color.BLACK);
         g.drawRoundRect(x,y,100,100,16,16);
         g.drawRoundRect(x-1,y-1,102,102,16,16);

         for (int i = 1; i <= 9; i++) {

            if (value >= 2) g.fillOval(x+15,y+15,20,20);
            if (value >= 4) g.fillOval(x+65,y+15,20,20);
            if (value == 6) g.fillOval(x+15,y+40,20,20);
            if (value % 2 != 0) g.fillOval(x+40,y+40,20,20);
            if (value == 6) g.fillOval(x+65,y+40,20,20);
            if (value >= 4) g.fillOval(x+15,y+65,20,20);
            if (value >= 2) g.fillOval(x+65,y+65,20,20);

         }

      }

      public void paintComponent(Graphics g) {

         Font font;

         super.paintComponent(g);

         font = new Font("Courier", Font.BOLD, 14);
         g.setColor(Color.BLACK);
         g.setFont(font);
         g.drawString("Click on the panel to roll the dice.", 7, 15);

         drawDie(g,v1,30,40);
         drawDie(g,v2,170,160);

         g.drawString("\u00A9", 50, 290);
         font = new Font("Courier", Font.PLAIN, 12);
         g.setFont(font);
         g.drawString("2011 by Dilip Muthukrishnan", 65, 290);

      }

   }

   public static class PairOfDiceMouse implements MouseListener {

      public void mousePressed(MouseEvent e) {

         PairOfDicePanel source = (PairOfDicePanel) e.getSource();
         source.v1 = (int) Math.round(1 + 5*Math.random());
         source.v2 = (int) Math.round(1 + 5*Math.random());
         source.repaint();

      }

      public void mouseReleased(MouseEvent e) {}
      public void mouseClicked(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}

   }

   public static void main(String[] args) {

      PairOfDicePanel myPanel = new PairOfDicePanel();
      Color color = new Color(200,200,255);
      myPanel.setBackground(color);
      myPanel.addMouseListener(new PairOfDiceMouse());

      JFrame myFrame = new JFrame("PairOfDice");
      myFrame.add(myPanel);
      myFrame.setSize(316, 338);
      myFrame.setLocation(100,100);
      myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      myFrame.setVisible(true);

   }


}