2. |
Next, you need to connect the buttons to actions. For each button, carry out these steps:
1. Create a class that implements the ActionListener interface and override the actionPerformed method. 2. Make an object of that class. 3. Install that object as the action listener of the button.
Perform these steps one at a time.
When the "Larger" button is clicked, we want to increase the font size by 25 percent. When the "Smaller" button is clicked, we want to decrease it. To avoid integer rounding errors, keep a floating-point variable fontSizeFactor that is initialized with 1. Clicking on the buttons multiplies by 1.25 or 0.8 (because 0.8 = 1/ 1.25).
Here is an appropriate action listener for the "Larger" button.
class LargerFontAction implements ActionListener { public void actionPerformed(ActionEvent event) { fontSizeFactor = 1.25 * fontSizeFactor; panel.setMessageSize((int)(fontSizeFactor * DEFAULT_SIZE)); } } This class is an inner class of the frame class since the actionPerformed method needs to access the panel and fontSizeFactor instance variables of the frame class.
To connect it to the "Larger" button, you need to create an object of this class and set it as an action listener of the button. Place the following instructions into the frame constructor:
LargerFontAction largerAction = new LargerFontAction(); largerButton.addActionListener(largerAction);
Add the code, compile the program, and run it.
Click on both buttons several times. What happens?
Answer:
|