Advertisement
Nick-O-Rama

DiceSimulator

Mar 12th, 2015
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import java.util.Random;
  5.  
  6. public class DiceSimulator extends JFrame{
  7.    
  8.     private JPanel dicePanel;
  9.     private JPanel buttonPanel;
  10.     private JButton button;
  11.     private JLabel dice1;
  12.     private JLabel dice2;
  13.     private String[] dice = {"C:\\Users\\Nicolas\\Pictures\\Dice\\die1.jpg",
  14.                              "C:\\Users\\Nicolas\\Pictures\\Dice\\die2.jpg",
  15.                              "C:\\Users\\Nicolas\\Pictures\\Dice\\die3.jpg",
  16.                              "C:\\Users\\Nicolas\\Pictures\\Dice\\die4.jpg",
  17.                              "C:\\Users\\Nicolas\\Pictures\\Dice\\die5.jpg",
  18.                              "C:\\Users\\Nicolas\\Pictures\\Dice\\die6.jpg"};
  19.    
  20.     public DiceSimulator()
  21.     {
  22.         super("Dice Simulator");
  23.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  24.         setLayout(new BorderLayout());
  25.        
  26.         buildDicePanel();
  27.         buildButtonPanel();
  28.        
  29.         add(dicePanel, BorderLayout.CENTER);
  30.         add(buttonPanel, BorderLayout.SOUTH);
  31.        
  32.         pack();
  33.         setVisible(true);
  34.     }
  35.    
  36.     public void buildDicePanel()
  37.     {
  38.         dicePanel = new JPanel();
  39.         dice1 = new JLabel("");
  40.         dice2 = new JLabel("");
  41.         dice1.setIcon(new ImageIcon(dice[0]));
  42.         dice2.setIcon(new ImageIcon(dice[0]));
  43.         dicePanel.add(dice1);
  44.         dicePanel.add(dice2);
  45.     }
  46.    
  47.     public void buildButtonPanel()
  48.     {
  49.         buttonPanel = new JPanel();
  50.         button = new JButton("Roll the Dice");
  51.         button.addActionListener(new ButtonListener());
  52.         buttonPanel.add(button);
  53.     }
  54.    
  55.     private class ButtonListener implements ActionListener
  56.     {
  57.         public void actionPerformed(ActionEvent e)
  58.         {
  59.             Random rand = new Random();
  60.             int roll1 = rand.nextInt(6);
  61.             int roll2 = rand.nextInt(6);
  62.             dice1.setIcon(new ImageIcon(dice[roll1]));
  63.             dice2.setIcon(new ImageIcon(dice[roll2]));
  64.             pack();
  65.         }
  66.     }
  67.    
  68.     public static void main(String[] args)
  69.     {
  70.         new DiceSimulator();
  71.     }
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement