Java Reference
In-Depth Information
This case study uses GUI components and events.
Key
Point
Now we will write the program for the loan-calculator problem presented at the beginning of
this chapter. Here are the major steps in the program:
1. Create the user interface, as shown in Figure 16.11.
a. Create a panel of a
GridLayout
with
5
rows and
2
columns. Add labels and text
fields to the panel. Set the title “Enter loan amount, interest rate, and years” for the
panel.
b. Create another panel with a
FlowLayout(FlowLayout.RIGHT)
and add a button
to the panel.
c. Add the first panel to the center of the frame and the second panel on the south side
of the frame.
2. Process the event.
Create and register the listener for processing the button-clicking action event. The
handler obtains the user input on the loan amount, interest rate, and number of years,
computes the monthly and total payments, and displays the values in the text fields.
JPanel
of
GridLayout (5, 2)
JPanel
of
Flowlayout
right aligned
F
IGURE
16.11
The program computes loan payments.
The complete program is given in Listing 16.7.
L
ISTING
16.7
LoanCalculator.java
1
import
java.awt.*;
2
import
java.awt.event.*;
3
import
javax.swing.*;
4
import
javax.swing.border.TitledBorder;
5
6
public class
LoanCalculator
extends
JFrame {
7
// Create text fields for interest rate, years,
8
// loan amount, monthly payment, and total payment
9
private
JTextField jtfAnnualInterestRate =
new
JTextField();
text fields
10
private
JTextField jtfNumberOfYears =
new
JTextField();
11
private
JTextField jtfLoanAmount =
new
JTextField();
12
private
JTextField jtfMonthlyPayment =
new
JTextField();
13
private
JTextField jtfTotalPayment =
new
JTextField();
14
15
// Create a Compute Payment button
16
private
JButton jbtComputeLoan =
new
JButton(
"Compute Payment"
);
button