Java Reference
In-Depth Information
In the isCurrentSelection() method, we just work through the array of Selection objects,
luckyNumbers , comparing each value with the possible argument using the hasValue() method.
If any button has the same value as possible , the method returns true , otherwise it returns false .
We're ready to start generating lottery entries. If you compile the Lottery.java file you can run the
applet using AppletViewer . You will need an HTML file of course. The following contents for the file
will do the job:
<APPLET CODE="Lottery.class" WIDTH=300 HEIGHT=200>
</APPLET>
You can adjust the width and height values to suit your monitor resolution if necessary.
The applet should produce a selection each time you click the left control button. Clicking on any of the
selection buttons will generate an action event that will cause a new value to be created for the button.
This enables you to replace any selection that you know to be unlucky with an alternative.
Undoubtedly, anyone who profits from using this applet will have immense feelings of gratitude and
indebtedness towards the author, who will not be offended in the slightest by any offers of a portion
of that success, however large!
Alternative Event Handling Approaches
As we indicated in the discussion, there are various approaches to implementing listeners. Let's look at a
couple of other ways in which we could have dealt with the control button events.
Instead of passing a constant to the listener class constructor to identify which button was selected, we
could have used the fact that the event object has a method, getSource() , that returns a reference to
the object that is the source of the event. To make use of this, a reference to both button objects would
need to be available to the actionPerformed() method. We could easily arrange for this to be the
case by adding a couple of fields to the Lottery class:
JButton pickButton = new JButton("Lucky Numbers!");
JButton colorButton = new JButton("Color");
The inner class could then be defined as:
class HandleControlButton implements ActionListener {
// Handle button click
public void actionPerformed(ActionEvent e) {
Object source = e.getSource(); // Get source object reference
if(source == pickButton) { // Is it the pick button?
int[] numbers = getNumbers(); // Get maxCount random numbers
for(int i = 0; i < numberCount; i++)
luckyNumbers[i].setValue(numbers[i]); // Set the button values
} else if(source == colorButton) { // Is it the color button?
Color color = new Color(
Search WWH ::




Custom Search