Java Reference
In-Depth Information
ically for each button by exclusive ORing the background and flipColor . As I said earlier, you must
get the RGB value for each color and operate on those — you can't apply the ^ operator to the object
references. You then turn the resulting RGB value back into a Color object.
Let's now add the inner class, Selection , which defines the lucky number buttons.
TRY IT OUT: Defining the Selection Buttons
Each button needs to store the value shown on the label, so the class needs a data member for this pur-
pose. The class also needs a constructor, a setValue() method to set the value for the button to a new
value, and a method to compare the current value for a button to a given value. You need to be able to set
the value for a button for two reasons — you need the capability when you set up all six selections in the
listener for the control button, and you want to reset the value for a button to change it individually.
The method to compare the value set for a button to a given integer enables you to exclude a number that
was already assigned to a button when you are generating a new set of button values. You also need to
implement the actionPerformed() method to handle the action events for the button, as the buttons are
going to handle their own events. Here's the basic code for the class definition:
private class Selection extends JButton implements ActionListener {
// Constructor
public Selection(int value) {
super(Integer.toString(value)); // Call base constructor and
set the label
this.value = value;
// Save
the value
setBackground(startColor);
setBorder(BorderFactory.createRaisedBevelBorder());
// Add
button border
setPreferredSize(new Dimension(80,20));
}
// Handle selection button event
public void actionPerformed(ActionEvent e) {
// Change this selection to a new selection
int candidate = 0;
while(true) {
// Loop to find a
different selection
candidate = VALUES[choice.nextInt(VALUES.length)];
if(!isCurrentSelection(candidate)) {
// If it
is different
break;
// end
the loop
}
}
setValue(candidate);
// We have one so
set the button value
Search WWH ::




Custom Search