This is a conversion of the previous AWT rolling dice example to Swing. Also not a "better" method for rendering the die. This continues the prelude to Swing based GUIs starting in the next section.
LangOneFConverted.java
source
Java Source --->
01: import javax.swing.*;
02: import java.awt.*;
03: import java.awt.event.*;
04:
05: public class LangOneFConverted extends JApplet implements ActionListener
06: {
07: JButton roll;
08: JDie dieOne, dieTwo;
09: Container c;
10:
11: public void init()
12: {
13: c = getContentPane();
14: c.setLayout(new FlowLayout());
15: c.setBackground(Color.white);
16: roll = new JButton("Roll");
17: c.add(roll);
18: roll.addActionListener(this);
19: dieOne = new JDie(2);
20: dieTwo = new JDie(5);
21: c.add(dieOne);
22: c.add(dieTwo);
23: }
24:
25: public void actionPerformed (ActionEvent e)
26: {
27: dieOne.rollDie();
28: dieTwo.rollDie();
29: }
30:
31: }
32:
33: class JDie extends JPanel
34: {
35: private int dieValue;
36:
37: public JDie(int value)
38: {
39: dieValue = value;
40: setBackground(Color.white);
41: }
42:
43: public void rollDie()
44: {
45: dieValue = (int)(Math.random()*6+1);
46: repaint();
47: }
48:
49: public Dimension getPreferredSize()
50: {
51: return new Dimension(70,70);
52: }
53:
54: public void paintComponent(Graphics g)
55: {
56: super.paintComponent(g);
57: g.setColor(Color.red);
58: g.fillRoundRect(0,0,70,70,20,20);
59: g.setColor(Color.white);
60:
61: //The following code provided by Chris Martian, CS4B Spring '03
62: // int[] x = {10, 50, 50, 10, 30, 30};
63: // int[] y = {10, 50, 10, 50, 10, 50};
64: // if (dieValue % 2 == 1)
65: // g.fillOval(30, 30, 10, 10);
66: // for (int i = 0; i < (dieValue / 2) * 2; i++)
67: // g.fillOval(x[i], y[i], 10, 10);
68:
69: //The following code provided by Tom Fangrow, CS4B Spring '06
70: int[] a = {30, 30, 10, 10, 50, 50, 50, 10, 10, 50, 30, 10, 30, 50};
71: for(int i = 2*(1-dieValue % 2); i < 2*(dieValue+1-dieValue % 2); i+=2)
72: g.fillOval(a[i], a[i+1], 10, 10);
73:
74: }
75: }