Java Reference
In-Depth Information
The listeners for each of the control buttons are of the same class type, so the listener object needs some
way to determine which button originated a particular event. One way to do this is to use constants as IDs
to identify the control buttons and pass the appropriate ID to the class constructor for the listener object.
You can define the constants
PICK_LUCKY_NUMBERS
and
COLOR
as fields in the
Lottery
class for this
purpose. The
COLOR
control button also references a couple of variables of type
Color
,
startColor
, and
flipColor
. You can add the following statements to the
Lottery
class after the definition of the
luck-
yNumbers
array:
// An array of custom buttons for the selected numbers
private Selection[] luckyNumbers = new Selection[NUMBER_COUNT];
final public static int PICK_LUCKY_NUMBERS = 1;
// Select
button ID
final public static int COLOR = 2;
// Color
button ID
// swap colors
Color flipColor = new
Color(Color.YELLOW.getRGB()^Color.RED.getRGB());
Color startColor = Color.YELLOW;
// start color
Directory "Lottery 1"
The
startColor
field is initialized with the
YELLOW
color from the
Color
class. The
flipColor
field is
set to the color that results from EORing the colors
YELLOW
and
RED
. Of course, to get a sensible color as
a result you must EOR the RGB values that you obtain from the
Color
objects, not the references to the
Color
objects! You use the
flipColor
field to change the color of the buttons.
The code to add the other panel and the control buttons is as follows:
// Create User Interface for applet
public void createGUI() {
// Setting up the selections buttons as previously...
// Add the pane containing control buttons
JPanel controlPane = new JPanel(new FlowLayout(FlowLayout.CENTER,
5, 10));
// Add the two control buttons
JButton button;
// A button
variable
Dimension buttonSize = new Dimension(100,20);
// Button size