img
After declaring the result variable, actionperformed( ) begins by obtaining the strings
from the three user-input text fields using the following sequence:
String amountStr = amountText.getText();
String periodStr = periodText.getText();
String rateStr = rateText.getText();
Next, it begins a try block and then verifies that all three fields actually contain
information, as shown here:
try {
if(amountStr.length() != 0 &&
periodStr.length() != 0 &&
rateStr.length() != 0) {
Recall that the user must enter the original loan amount, the number of years for the
loan, and the interest rate. If all three text fields contain information, then the length of each
string will be greater than zero.
If the user has entered all the loan data, then the numeric values corresponding to those
strings are obtained and stored in the appropriate instance variable. Next, compute( ) is
called to compute the loan payment, and the result is displayed in the read-only text field
referred to by paymentText, as shown here:
principal = Double.parseDouble(amountStr);
numYears = Double.parseDouble(periodStr);
intRate = Double.parseDouble(rateStr) / 100;
result = compute();
paymentText.setText(nf.format(result));
Notice the call to nf.format(result). This causes the value in result to be formatted as
previously specified (with two decimal digits) and the resulting string is returned. This
string is then used to set the text in the JTextField specified by paymentText.
If the user has entered a nonnumeric value into one of the text fields, then
Double.parseDouble( ) will throw a NumberFormatException. If this happens, an error
message will be displayed on the status line and the Payment text field will be emptied, as
shown here:
showStatus(""); // erase any previous error message
} catch (NumberFormatException exc) {
showStatus("Invalid Data");
paymentText.setText("");
}
Otherwise, any previously reported error is removed.
The compute( ) Method
The calculation of the loan payment takes place in compute( ). It implements the formula
shown earlier and operates on the values in principal, intRate, numYears, and payPerYear.
It returns the result.
NOTE  The basic skeleton used by RegPay is used by all the applets shown in this chapter.
OTE
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home