Java Reference
In-Depth Information
}
// Set the value for the selection
public void setValue(int value) {
setText(Integer.toString(value));
// Set value as
the button label
this.value = value;
// Save the value
}
// Check the value for the selection
boolean hasValue(int possible) {
return value==possible;
// Return true if
equals current value
}
// Check the current choices
boolean isCurrentSelection(int possible) {
for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
// For each button
if(luckyNumbers[i].hasValue(possible)) {
// check against
possible
return true;
// Return true for
any =
}
}
return false;
// Otherwise return false
}
private int value;
// Value for the
selection button
}
Directory "Lottery 1"
How It Works
The constructor calls the base class constructor to set the initial label for the button. It also stores the
value of type
int
that is passed as an argument. The
setValue()
method just updates the value for
a selection button with the value passed as an argument and changes the button label by calling the
setText()
method, which is inherited from the base class,
JButton
. The
hasValue()
method returns
true
if the argument value passed to it is equal to the current value stored in the data member value and
returns
false
otherwise.
The
actionPerformed()
method has a little more meat to it, but the technique is similar to that in the
getNumbers()
method. To change the selection, you must create a new random value for the button from
the numbers in the
VALUES
array, but excluding all the numbers currently assigned to the six buttons. To
do this you just check each candidate against the six existing selections by calling the
isCurrentSelec-
tion()
method and continue choosing a new candidate until you find one that's different.
In the
isCurrentSelection()
method, you just work through the array of
Selection
objects,
luck-
yNumbers
, comparing each value with the
possible
argument using the
hasValue()
method. If any but-
ton has the same value as
possible
, the method returns
true
; otherwise, it returns
false
.