Java Reference
In-Depth Information
}
result[sum] = result[sum] + 1;
return result;
}
Today's next project is a Swing application that rolls three 6-sided dice a user-selected
number of times and tabulates the results. Sixteen text fields represent the possible val-
ues, which range from 3 to 18.
The application is developed as two classes: the DiceRoller frame that holds the graphi-
cal user interface and the DiceWorker Swing worker that handles the dice rolls.
Because the application allows the user to roll the dice thousands or even millions of
times, putting this task in a worker keeps the Swing interface responsive to user input.
Listing 14.2 contains the worker class, DiceWorker .
LISTING 14.2
The Full Text of DiceWorker.java
1: import javax.swing.*;
2:
3: public class DiceWorker extends SwingWorker {
4: int timesToRoll;
5:
6: // set up the Swing worker
7: public DiceWorker(int timesToRoll) {
8: super();
9: this.timesToRoll = timesToRoll;
10: }
11:
12: // define the task the worker performs
13: protected int[] doInBackground() {
14: int[] result = new int[16];
15: for (int i = 0; i < this.timesToRoll; i++) {
16: int sum = 0;
17: for (int j = 0; j < 3; j++) {
18: sum += Math.floor(Math.random() * 6);
19: }
20: result[sum] = result[sum] + 1;
21: }
22: // transmit the result
23: return result;
24: }
25: }
14
You can compile this class, but there's no way to do anything with it until the next class,
DiceRoller , has been created.
 
Search WWH ::




Custom Search