Java Reference
In-Depth Information
}
// Handle selection button event
public void actionPerformed(ActionEvent e) {
// Change this selection to a new selection
int candidate = 0;
for(;;) { // Loop to find a different selection
candidate = values[choice.nextInt(values.length)];
if(isCurrentSelection(candidate)) // If it is not different
continue; // find another
setValue(candidate); // We have one so set the button value
return;
}
}
// 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 < numberCount; 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
}
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 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, we must create a new random value for the
button from the numbers values array, but excluding all the numbers currently assigned to the six
buttons. To do this we just check each candidate against the six existing selections by calling the
isCurrentSelection() , and continue choosing a new candidate until we find one that's different.
Search WWH ::




Custom Search