19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

16.7 Case Study: Loan Calcula<strong>to</strong>r 615<br />

16.7 Case Study: Loan Calcula<strong>to</strong>r<br />

This case study uses GUI <strong>com</strong>ponents and events.<br />

Now we will write the program for the loan-calcula<strong>to</strong>r problem presented at the beginning of<br />

this chapter. Here are the major steps in the program:<br />

1. Create the user interface, as shown in Figure 16.11.<br />

a. Create a panel of a GridLayout with 5 rows and 2 columns. Add labels and text<br />

fields <strong>to</strong> the panel. Set the title “Enter loan amount, interest rate, and years” for the<br />

panel.<br />

b. Create another panel with a FlowLayout(FlowLayout.RIGHT) and add a but<strong>to</strong>n<br />

<strong>to</strong> the panel.<br />

c. Add the first panel <strong>to</strong> the center of the frame and the second panel on the south side<br />

of the frame.<br />

2. Process the event.<br />

Create and register the listener for processing the but<strong>to</strong>n-clicking action event. The<br />

handler obtains the user input on the loan amount, interest rate, and number of years,<br />

<strong>com</strong>putes the monthly and <strong>to</strong>tal payments, and displays the values in the text fields.<br />

Key<br />

Point<br />

JPanel of<br />

GridLayout (5, 2)<br />

JPanel of Flowlayout<br />

right aligned<br />

FIGURE 16.11<br />

The program <strong>com</strong>putes loan payments.<br />

The <strong>com</strong>plete program is given in Listing 16.7.<br />

LISTING 16.7<br />

LoanCalcula<strong>to</strong>r.java<br />

1 import java.awt.*;<br />

2 import java.awt.event.*;<br />

3 import javax.swing.*;<br />

4 import javax.swing.border.TitledBorder;<br />

5<br />

6 public class LoanCalcula<strong>to</strong>r extends JFrame {<br />

7 // Create text fields for interest rate, years,<br />

8 // loan amount, monthly payment, and <strong>to</strong>tal payment<br />

9 private JTextField jtfAnnualInterestRate = new JTextField();<br />

10 private JTextField jtfNumberOfYears = new JTextField();<br />

11 private JTextField jtfLoanAmount = new JTextField();<br />

12 private JTextField jtfMonthlyPayment = new JTextField();<br />

13 private JTextField jtfTotalPayment = new JTextField();<br />

14<br />

15 // Create a Compute Payment but<strong>to</strong>n<br />

16 private JBut<strong>to</strong>n jbtComputeLoan = new JBut<strong>to</strong>n("Compute Payment");<br />

text fields<br />

but<strong>to</strong>n

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!