Enhance the Car Payment Calculator application to use the Java Speech API (Fig. 28.21). When the user clicks the Instructions JButton, the application should explain the purpose of the applica- tion. After the user enters information into each field of the Car Payment Calculator and clicks the Calculate JButton, the application should speak the calculated payment amounts and the period (number of months) over which they were calculated.



a) Copying the template to your working directory. Copy the C:Examples Tutorial28ExercisesCarPaymentCalculatorEnhancement directory to your C:SimplyJava directory.

b) Opening the template file. Open the CarPayment.java file in your text editor.

c) Importing Java Speech API packages. Import the javax.speech and the

javax.speech.synthesis packages.

d) Declaring instance variables. At line 34, declare an instance variable of type Syn- thesizer, which is used to speak text.

e) Creating a Synthesizer object. Inside the CarPayment constructor, create a Synthe- sizer object, allocate the resource and get the synthesizer ready to speak.

f) Adding code to the instructionsJButtonActionPerformed method. Find the instructionsJButtonActionPerformed method, which immediately follows createUserInterface. Add code to the instructionsJButtonActionPerformed method to use the speech synthesizer. Have the synthesizer tell the user to enter the price of a c


```
1 // Exercise 28.16: CarPayment.java
2 // Calculate different billing plans for a car loan.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6 import java.text.DecimalFormat;
7 import java.util.*;
8 import javax.speech.*;
9 import javax.speech.synthesis.*;
10
11 public class CarPayment extends JFrame
12 {
13 // JLabel and JTextField for price
14 private JLabel priceJLabel;
15 private JTextField priceJTextField;
16
17 // JLabel and JTextField for down payment
18 private JLabel downPaymentJLabel;
19 private JTextField downPaymentJTextField;
20
21 // JLabel and JTextField for interest
22 private JLabel interestJLabel;
23 private JTextField interestJTextField;
24
25 // JButton for instructions
26 private JButton instructionsJButton;
27
28 // JButton to initiate calculation
29 private JButton calculateJButton;
30
31 // JTextArea to display results
32 private JTextArea paymentsJTextArea;
33
34 // Synthesizer to speak text
35 private Synthesizer speechSynthesizer;
36
37 // no-argument constructor
38 public CarPayment()
39 {
40 // initialize Synthesizer
41 try
42 {
43 // create SynthesizerModeDesc for FreeTTS synthesizer.
44 SynthesizerModeDesc descriptor = new SynthesizerModeDesc(
45 "Unlimited domain FreeTTS Speech Synthesizer from " +
46 "Sun Labs", null, Locale.US, Boolean.FALSE, null );
47
48 // create a Synthesizer
49 speechSynthesizer =
50 Central.createSynthesizer( descriptor );
51
52 // Synthesizer created successfully
53 if ( speechSynthesizer != null )
54 {
55 // get synthesizer ready to speak
56 speechSynthesizer.allocate();
57 speechSynthesizer.resume();
58
59 // get synthesizer properties
60 SynthesizerProperties properties =
61 speechSynthesizer.getSynthesizerProperties();
62
63 // set up speaking rate
64 properties.setSpeakingRate( 100.0f );
65
66
67
68 {
69 System.err.println( "Synthesizer creation failed." );
70 System.exit( 1 );
71 }
72
73 } // end try
74
75 catch ( Exception myException )
76 {
77 myException.printStackTrace();
78 }
79
80 createUserInterface(); // set up GUI
81
82 } // end CarPayment constructor
83
84 // create and position GUI components; register event handlers
85 private void createUserInterface()
86 {
87 // get content pane for attaching GUI components
88 Container contentPane = getContentPane();
89
90 // enable explicit positioning of GUI components
91 contentPane.setLayout( null );
92
93 // set up priceJLabel
94 priceJLabel = new JLabel();
95 priceJLabel.setBounds( 40, 24, 80, 21 );
96 priceJLabel.setText( "Price:" );
97 contentPane.add( priceJLabel );
98
99 // set up priceJTextField
100 priceJTextField = new JTextField();
101 priceJTextField.setBounds( 184, 24, 56, 21 );
102 priceJTextField.setHorizontalAlignment( JTextField.RIGHT );
103 contentPane.add( priceJTextField );
104
105 // set up downPaymentJLabel
106 downPaymentJLabel = new JLabel();
107 downPaymentJLabel.setBounds( 40, 56, 96, 21 );
108 downPaymentJLabel.setText( "Down payment:" );
109 contentPane.add( downPaymentJLabel );
110
111 // set up downPaymentJTextField
112 downPaymentJTextField = new JTextField();
113 downPaymentJTextField.setBounds( 184, 56, 56, 21 );
114 downPaymentJTextField.setHorizontalAlignment(
115 JTextField.RIGHT );
116 contentPane.add( downPaymentJTextField );
117
118 // set up interestJLabel
119 interestJLabel = new JLabel();
120 interestJLabel.setBounds( 40, 88, 120, 21 );
121 interestJLabel.setText( "Annual interest rate:" );
122 contentPane.add( interestJLabel );
123
124 // set up interestJTextField
125 interestJTextField = new JTextField();
126 interestJTextField.setBounds( 184, 88, 56, 21 );
127 interestJTextField.setHorizontalAlignment( JTextField.RIGHT );
128 contentPane.add( interestJTextField );
129
130 // set up instructionsJButton and register its event handler
131 instructionsJButton = new JButton();
132 instructionsJButton.setBounds( 40, 128, 110, 24 );
133 instructionsJButton.setText( "Instructions" );
134 contentPane.add( instructionsJButton );
135 instructionsJButton.addActionListener(
136
137 new ActionListener() // anonymous inner class
138 {
139 // event handler called when instructionsJButton
140 // is clicked
141 public void actionPerformed( ActionEvent event )
142 {
143 instructionsJButtonActionPerformed( event );
144 }
145
146 } // end anonymous inner class
147
148 ); // end call to addActionListener
149
150 // set up calculateJButton and register its event handler
151 calculateJButton = new JButton();
152 calculateJButton.setBounds( 155, 128, 90, 24 );
153 calculateJButton.setText( "Calculate" );
154 contentPane.add( calculateJButton );
155 calculateJButton.addActionListener(
156
157 new ActionListener() // anonymous inner class
158 {
159 // event handler called when calculateJButton is clicked
160 public void actionPerformed( ActionEvent event )
161 {
162 calculateJButtonActionPerformed( event );
163 }
164
165 } // end anonymous inner class
166
167 ); // end call to addActionListener
168
169 // set up paymentsJTextArea
170 paymentsJTextArea = new JTextArea();
171 paymentsJTextArea.setBounds( 28, 168, 232, 90 );
172 paymentsJTextArea.setEditable( false );
173 contentPane.add( paymentsJTextArea );
174
175 // set properties of application's window
176 setTitle( "Car Payment Calculator" ); // set title bar string
177 setSize( 288, 302 ); // set window's size
178 setVisible( true ); // display window
179
180 // ensure synthesizer is cleaned up
181 // when user closes application
182 addWindowListener(
183
184 new WindowAdapter() // anonymous inner class
185 {
186 public void windowClosing( WindowEvent event )
187 {
188 frameWindowClosing( event );
189 }
190
191 } // end anonymous inner class
192
193 ); // end addWindowListener
194
195 } // end method createUserInterface
196
197 // method called when user clicks instructionsJButton
198 private void instructionsJButtonActionPerformed(
199 ActionEvent event )
200 {
201 speechSynthesizer.speakPlainText( "To calculate the car " +
202 "payment, you need to enter the price of a car, the " +
203 "down-payment amount and the annual interest rate of " +
204 "the loan. After you input this information, click " +
205 "the calculate button. I will calculate the monthly " +
206 "payments you will need to make for two, three, four " +
207 " and five-year loans.", null );
208
209 } // end method instructionsJButtonActionPerformed
210
211 // method called when user clicks calculateJButton
212 private void calculateJButtonActionPerformed( ActionEvent event )
213 {
214 int years = 2; // repetition counter
215 int months; // payment period
216 double monthlyPayment; // monthly payment
217
218 // clear JTextArea
219 paymentsJTextArea.setText( "" );
220
221 // add header JTextArea
222 paymentsJTextArea.append( "Months\tMonthly Payments" );
223
224 // retrieve user input
225 int price = Integer.parseInt( priceJTextField.getText() );
226 int downPayment =
227 Integer.parseInt( downPaymentJTextField.getText() );
228 double interest =
229 Double.parseDouble( interestJTextField.getText() );
230
231 // calculate loan amount and monthly interest
232 int loanAmount = price - downPayment;
233 double monthlyInterest = interest / 1200;
234
235 // compose text to speak
236 String textToSpeak = "You will have to pay: ";
237
238 // format to display monthlyPayment in currency format
239 DecimalFormat dollars = new DecimalFormat( "$0.00" );
240
241 // while years is less than or equal to five years
242 while ( years <= 5 )
243 {
244 // calculate payment period
245 months = 12 * years;
246
247 // get monthlyPayment
248 monthlyPayment = calculateMonthlyPayment(
249 monthlyInterest, months, loanAmount );
250
251 // insert result into JTextArea
252 paymentsJTextArea.append( "\n" + months + "\t" +
253 dollars.format( monthlyPayment ) );
254
255 // specify format of payment values for first four years
256 if ( years < 5 )
257 {
258 textToSpeak = textToSpeak + dollars.format(
259 monthlyPayment ) + " per month, over " + months +
260 " months, ";
261 }
262 else
263 {
264 // specify format for payment value of fifth year
265 textToSpeak = textToSpeak + "or " + dollars.format(
266 monthlyPayment ) + " per month, over " + months +
267 " months.";
268 }
269
270 years++; // increment counter
271
272 } // end while
273
274 speechSynthesizer.speakPlainText( textToSpeak, null );
275
276 } // end method calculateJButtonAction

Computer Science & Information Technology

You might also like to view...

Software for creating PDFs is included with the Mac OS X operating system.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology

The process of assuring that parties to a transaction are authentic, so that they cannot later deny having participated is called repudiation.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology

Mobile devices are critical to an application's security. Therefore, stringent rules should be followed to ensure they are never lost or damaged.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology

Because the square root of a negative number is not defined, what is the result of this statement: System.out.println (Math.sqrt(-16));

A. Runtime error message B. Syntax error C. NaN D. -4

Computer Science & Information Technology