Last semester you worked with GUIs in lab 12, where
you wrote event-driven programs that did things when the user pushed a button (remember
Vote For Joe?). Recall that these programs used ActionListeners to carry out
certain actions when a button was pressed.
In today's exercise you will see two new GUI components (checkboxes and radio buttons)
along with their listeners (ItemListeners and ActionListeners respectively).
You will also work with them in a standalone program instead of an applet.
The files StyleOptions.java and
StyleGUI.java are adapted from Listings 6.18
and 6.19 of the text. (A variable
fontSize is used rather than the constant FONT_SIZE and the
variable style is an instance variable rather than local to the
itemStateChanged method). Save these files to your directory and compile and
run StyleOptions.java to see how it works. This is the driver; StyleGUI.java contains
the code for the GUI.
Now you will add a set
of 3 radio buttons to let the user choose among three font sizes. The
method of adding the radio buttons will be very similar to that in the
QuoteGUI class (Listing 6.21 of the text), so study this example before you
continue.
Do the following to add the radio buttons to the GUI:
- Declare three objects small, medium, and
large of type JRadioButton.
- Instantiate the button objects labeling them "Small Font," "Medium Font,"
"Large Font." Initialize the large font button to true. Set the
background color of the buttons to cyan.
- Instantiate a button group object and add the buttons to
it.
- Radio buttons produce action events so you need to add an inner
class (name it SizeListener) to implement ActionListener and
listen for radio button clicks. The code for actionPerformed
can be similar to that in the QuoteListener in Listing 6.21. (Or if you prefer,
you can use the isSelected method to see which button was selected
instead of getting and checking the source.)
You need to set the fontSize variable (use 12 for small,
24 for medium, and 36 for large) in the if statement, then call the
setFont method to set the font for the saying object.
- In StyleGUI() instantiate a SizeListener and add it
to each button. Also add each button to the panel.
- Compile and run the program. Note that as the font size changes
the checkboxes and buttons re-arrange themselves in the panel. You
will learn how to control layout later in the course.