Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

934 Part IV: Applying Java


gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(paymentText, gbc);

gbc.anchor = GridBagConstraints.CENTER;
gbag.setConstraints(doIt, gbc);

// Add all the components.
add(heading);
add(amountLab);
add(amountText);
add(periodLab);
add(periodText);
add(rateLab);
add(rateText);
add(paymentLab);
add(paymentText);
add(doIt);

// Register to receive action events.
amountText.addActionListener(this);
periodText.addActionListener(this);
rateText.addActionListener(this);
doIt.addActionListener(this);

// Create a number format.
nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
}

/* User pressed Enter on a text field or
pressed Compute. Display the result if all
fields are completed. */
public void actionPerformed(ActionEvent ae) {
double result = 0.0;

String amountStr = amountText.getText();
String periodStr = periodText.getText();
String rateStr = rateText.getText();

try {
if(amountStr.length() != 0 &&
periodStr.length() != 0 &&
rateStr.length() != 0) {

principal = Double.parseDouble(amountStr);
numYears = Double.parseDouble(periodStr);
intRate = Double.parseDouble(rateStr) / 100;

result = compute();

paymentText.setText(nf.format(result));
}

showStatus(""); // erase any previous error message
Free download pdf