Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

208 HOUR 15:Responding to User Input


Instead of using probability to figure this problem out, the computer con-
ducts drawings in rapid succession and doesn’t stop until there’s a winner.
Because the 6-out-of-6 win is extremely unlikely, the program also reports
on any combination of three, four, or five winning numbers.
The interface includes 12 text fields for lotto numbers and two check boxes
labeled Quick Pick and Personal. Six text fields, disabled for input, are
used to display the winning numbers of each drawing. The other six text
fields are for the user’s choice of numbers. Selecting the Quick Pick box
chooses six random numbers for a user. Selecting Personal enables the user
to select desired numbers.
Three buttons control the activity of the program: Stop, Play, and Reset.
When the Play button is pressed, the program starts a thread called
playingand generates Lotto drawings.
Pressing the Stop button stops the thread, and pressing Reset clears all
fields so the user can start over. You learn about threads in Hour 19,
“Creating a Threaded Program.”
TheLottoEventclass implements three interfaces: ActionListener,
ItemListener, and Runnable. The Runnable interface relates to threads
and is covered in Hour 19. The listeners are needed to listen to user events
generated by the application’s buttons and check boxes. The program does
not need to listen to any events related to the text fields because they are
used strictly to store the user’s choice of numbers. The user interface han-
dles this storage automatically.
The class requires the use of the main Swing package, javax.swing, and
Java’s event-handling package, java.awt.event.
The class has two instance variables:

. gui, a LottoMadnessobject
. playing, a Threadobject used to conduct continuous lotto drawings


The guivariable is used to communicate with the LottoMadnessobject that
contains the program’s GUI. When you need to make a change to the inter-
face or retrieve a value from one of its text fields, you use the guiobject’s
instance variables.
For example, the playinstance variable of LottoMadnessrepresents the
Play button. To disable this button in LottoEvent, you can use the follow-
ing statement:
gui.play.setEnabled(false);
Free download pdf