Chapter 32: Financial Applets and Servlets 937
amountText = new JTextField(10);
periodText = new JTextField(10);
paymentText = new JTextField(10);
rateText = new JTextField(10);
// Payment field for display only.
paymentText.setEditable(false);
doIt = new JButton("Compute");
Notice that the text field that displays the monthly payment is set to read-only by calling
setEditable(false). This causes the field to be grayed and no text can be entered into the
field by the user. However, the contents of the text field can still be set by callingsetText( ).
Thus, when editing is disabled in aJTextField, the field can be used to display text, but the
text cannot be changed by the user.
Next, the grid bag constraints for each component are set by the following code sequence:
// Define the grid bag.
gbc.weighty = 1.0; // use a row weight of 1
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.NORTH;
gbag.setConstraints(heading, gbc);
// Anchor most components to the right.
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(amountLab, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(amountText, gbc);
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(periodLab, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(periodText, gbc);
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(rateLab, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(rateText, gbc);
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(paymentLab, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(paymentText, gbc);
gbc.anchor = GridBagConstraints.CENTER;
gbag.setConstraints(doIt, gbc);
Although this seems a bit complicated at first glance, it really isn’t. Just remember that
each row in the grid is specified separately. Here is how the sequence works. First, the
weight of each row, contained ingbc.weighty, is set to 1. This tells the grid bag to distribute
extra space evenly when there is more vertical space than needed to hold the components.