November 2002
Intermediate to advanced
1278 pages
38h 26m
English
One of the most common user-interface constructs is the basic
form. Typically, forms are made up of labels and fields,
with the label describing the text to be entered in the field. Here’s a
primitive TextForm class that shows
the use of mnemonics, tooltips, and basic accessibility support. Note
that we call setLabelFor( ) to
associate each label with a text field. This association allows the
mnemonics to set the focus and, together with setToolTipText( ), supports accessibility (see
Chapter 25).
// TextForm.j ava // import javax.swing.*; import java.awt.event.*; import java.awt.*; // A simple label/field form panel public class TextForm extends JPanel { private JTextField[] fields; // Create a form with the specified labels, tooltips, and sizes. public TextForm(String[] labels, char[] mnemonics, int[] widths, String[] tips) { super(new BorderLayout( )); JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1)); JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1)); add(labelPanel, BorderLayout.WEST); add(fieldPanel, BorderLayout.CENTER); fields = new JTextField[labels.length]; for (int i=0; i < labels.length; i+=1) { fields[i] = new JTextField( ); if (i < tips.length) fields[i].setToolTipText(tips[i]); if (i < widths.length) fields[i].setColumns(widths[i]); JLabel lab = new JLabel(labels[i], JLabel.RIGHT); lab.setLabelFor(fields[i]); if (i < mnemonics.length) lab.setDisplayedMnemonic(mnemonics[i]); labelPanel.add(lab); JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT)); ...