Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

936 Part IV: Applying Java


RegPaythen declares threedoublevariables that hold the loan values. The original
principal is stored inprincipal, the interest rate is stored inintRate, and the length of the
loan in years is stored innumYears. These values are entered by the user through the text
fields. Next, thefinalinteger variablepayPerYearis declared and initialized to 12. Thus, the
number of payments per year is hard-coded to monthly because this is the way that most
loans are paid. As the comments suggest, you could allow the user to enter this value, but
doing so will require another text field.
The last instance variable declared byRegPayisnf, a reference to an object of type
NumberFormat, which will describe the number format used for output.NumberFormat
is stored in thejava.textpackage. Although there are other ways to format numeric output,
such as by using theFormatterclass,NumberFormatis a good choice in this case, because
the same format is used repeatedly, and this format can be set once, at the start of the
program. The financial applets also offer a good opportunity to demonstrate its use.

The init( ) Method

Like all applets, theinit( )method is called when the applet first starts execution. This
method simply invokes themakeGUI( )method on the event-dispatching thread. As
explained in Chapter 29, Swing-based applets must construct and interact with GUI
components only through the event-dispatching thread.

The makeGUI( ) Method

ThemakeGUI( )method sets up the user interface for the applet. It performs the following jobs:


  1. It changes the layout manager toGridBagLayout.

  2. It instantiates the various GUI components.

  3. It adds the components to the grid bag.

  4. It adds action listeners for the components.


Let’s now look atmakeGUI( )line by line. The method begins with these lines of code:

// Use a grid bag layout.
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);

This sequence creates aGridBagLayoutlayout manager that will be used by the applet. (For
details on usingGridBagLayout, see Chapter 24.)GrigBagLayoutis used because it allows
detailed control over the placement of controls within an applet.
Next,makeGUI( )creates the label components, text fields, and Compute button, as
shown here:

JLabel heading = new
JLabel("Compute Monthly Loan Payments");

JLabel amountLab = new JLabel("Principal ");
JLabel periodLab = new JLabel("Years ");
JLabel rateLab = new JLabel("Interest Rate ");
JLabel paymentLab = new JLabel("Monthly Payments ");
Free download pdf