938 Part IV: Applying Java
Next, thegbc.gridwidthis set toREMAINDER, andgbc.anchoris set toNORTH. The label
referred to byheadingis added by callingsetConstraints( )ongbag. This sequence sets the
location ofheadingto the top of the grid (north) and gives it the remainder of the row.
Thus, after this sequence executes, the heading will be at the top of the window and on a
row by itself.
Next, the four text fields and their labels are added. First,gbc.anchoris set toEAST.
This causes each component to be aligned to the right. Next,gbc.gridWidthis set to
RELATIVE, and the label is added. Then,gbc.gridWidthis set toREMAINDER, and the
text field is added. Thus, each text field and label pair occupies one row. This process
repeats until all four text field and label pairs have been added. Finally, the Compute button
is added in the center.
After the grid bag constraints have been set, the components are actually added to the
window by the following code:
// Add all the components.
add(heading);
add(amountLab);
add(amountText);
add(periodLab);
add(periodText);
add(rateLab);
add(rateText);
add(paymentLab);
add(paymentText);
add(doIt);
Next, action listeners are registered for the three input text fields and the Compute
button, as shown here:
// Register to receive action events.
amountText.addActionListener(this);
periodText.addActionListener(this);
rateText.addActionListener(this);
doIt.addActionListener(this);
Finally, aNumberFormatobject is obtained and the format is set to two decimal digits:
// Create a number format.
nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
The call to the factory methodgetInstance( )obtains aNumberFormatobject suitable for the
default locale. The calls tosetMinimumFractionDigits( )andsetMaximumFractionDigits( )
set the minimum and maximum number of decimal digits to be displayed. Because both are set
to two, this ensures that two decimal places will always be visible.
The actionPerformed( ) Method
TheactionPerformed( )method is called whenever the user pressesENTERwhen in a text
field or clicks the Compute button. This method performs three main functions: it obtains
the loan information entered by the user, it callscompute( )to find the loan payments, and
it displays the result. Let’s now examineactionPerformed( )line by line.