Java Reference
In-Depth Information
// Handle button click
public void actionPerformed(ActionEvent e) {
// Handle button click for a particular button...
}
// Rest of the inner class definition...
}
final static int numberCount = 6; // Number of lucky numbers
final static int minValue = 1; // Minimum in range
final static int maxValue = 49; // Maximum in range
static int[] values = new int[maxValue-minValue+1]; // Array of possible values
static { // Initialize array
for(int i = 0 ; i<values.length ; i++)
values[i] = i + minValue;
}
// An array of custom buttons for the selected numbers
private Selection[] luckyNumbers = new Selection[numberCount];
private static Random choice = new Random(); // Random number generator
}
How It Works
The applet class is called
Lottery
and it contains two inner classes,
Selection
and
HandleControlButton
. The
Selection
class provides a custom button that will show a number as
its label, the number being passed to the constructor as an argument. We can make an object of the
Selection
class listen for its own action events. As we said at the outset, an event for a selection
button will change the label of the button to a different value so of course we'll need to make sure this
doesn't duplicate any of the values for the other buttons.
The two control buttons will use separate listeners to handle their action events and the response to an
event will be quite different for each of them. One control button will create a new set of lucky numbers
while the other control button will just change the color of the buttons.
The
numberCount
member of the
Lottery
class sets the number of values that is created. The
minValue
and
maxValue
members specify the range of possible values. The possible values for
selections are stored in the
values
array, and this is set up in the static initialization block. The
Lottery
class has an array of
Selection
objects as a data member - we can have arrays of
components just like arrays of any other kind of object. Since the
Selection
buttons will all be the
same, it's very convenient to create them as an array, and having an array of components will enable us
to set them up in a loop. We also have a
Random
object as a member as we will need to generate some
random integers.
We can now set about filling in the sections of the program that we roughed out previously.
Filling in the Details
To generate
maxCount
random values from the elements in the
values
array is quite independent of
everything else here, so we'll define a static method in the
Lottery
class to do this.