|
|
Using the JFC/Swing Packages |
Text fields display a single line of selectable, optionally editable text. Generally you use theJTextFieldclass to provide text fields. If you need to provide a password field -- an editable text field that doesn't show the characters the user types -- use the
JPasswordFieldclass instead. See the
PasswordDemoexample described in Using theSwingWorkerClass for an example of using aJPasswordField.If you want to provide some strings for the user to choose from, consider using an editable combo box. If you need to obtain more than one line of input from the user, then you should use one of the classes that implements a general-purpose text area.
The loan calculator shown in the following figure uses four
JTextFieldinstances. EachJTextFieldhas an accompanyingJLabelthat describes it. The user enters loan information into the first three text fields, then presses the return key. The program computes the monthly payment and displays the result in the fourth text field.
Try this:
- Compile and run the application. The source file is
LoanCalc.java.
See Getting Started with Swing if you need help.- Enter information into the text fields and see the results.
If you enter invalid data, the program displays an error message. This program uses a class calledjava.text.NumberFormatto format and parse the numbers in the text fields. BecauseNumberFormatis locale-sensitive, it is covered in the internationalization trail. See Number Formattingfor more information.
- Try to type into the fourth text field.
You can't because it isn't editable. However, you can select the text.- Resize the window.
Note how the labels and text fields remain aligned. Laying Out Label/Text Field Pairs talks more about this feature of the program.
Below is the code from
LoanCalc.javathat creates the text fields in the previous example.setUpFormatters(); . . . //Create the text fields and set them up amountField = new JTextField(moneyFormatter.format(amount), 10); amountField.addActionListener(new TextFieldListener(moneyFormatter)); rateField = new JTextField(percentFormatter.format(rate), 10); rateField.addActionListener(new TextFieldListener(percentFormatter)); numPeriodsField = new JTextField(integerFormatter.format(numPeriods), 10); numPeriodsField.addActionListener(new TextFieldListener(integerFormatter)); paymentField = new JTextField(moneyFormatter.format(payment), 10); paymentField.setEditable(false); paymentField.setForeground(Color.red); . . .Laying Out Label/Text Field Pairs
Rows of label and text field pairs such as those found in the loan calculator are quite common on preference panels and panels that implement forms. Here's the code that lays out the lable and text field pairs.You may be surprised to find that the labels are laid out without reference to the text fields and, in fact, are in a different panel, yet align correctly with them. This is a side effect of the layout managers used by the program.. . . //Layout the labels in a panel JPanel labelPane = new JPanel(); labelPane.setLayout(new GridLayout(0, 1)); labelPane.add(amountLabel); labelPane.add(rateLabel); labelPane.add(numPeriodsLabel); labelPane.add(paymentLabel); //Layout the text fields in a panel JPanel fieldPane = new JPanel(); fieldPane.setLayout(new GridLayout(0, 1)); fieldPane.add(amountField); fieldPane.add(rateField); fieldPane.add(numPeriodsField); fieldPane.add(paymentField); //Put the panels in another panel, labels on left, //text fields on right JPanel contentPane = new JPanel(); contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); contentPane.setLayout(new BorderLayout()); contentPane.add(labelPane); contentPane.add(fieldPane, "East"); setContentPane(contentPane); . . .As the diagram illustrates, the program uses twoGridLayoutmanagers, one to lay out the column of labels and one for the column of text fields.GridLayoutguarantees that all of its components are the same size, so all of the text fields are the same height and all of the labels are the same height.To get the labels and the text fields to align, the program uses a third layout manager, a
BorderLayout. With just two components at East and Center,BorderLayoutguarantees the columns are the same height. Thus, the labels and the text fields align.Another way to get labels and text fields to align is to use the AWT's most flexible, complex layout manager:
GridBagLayout.
The Text Field API
The following tables list the commonly usedJTextFieldconstructors and methods. Other methods you're likely to call are defined by theJComponentand
Componentclasses. They include
Component'ssetForeground,setBackground, andsetFontmethods. [CHECK: is that right? any other particularly useful Component/JComponent methods?] [Link to JComponent and Component discussions.]The API for using text fields falls into three categories:
- Setting or Getting the Text Field's Contents
- Fine Tuning the Text Field's Appearance
- Handling Events from a Text Field
Setting or Getting the Text Field's Contents Method or Constructor Purpose
JTextField()
JTextField(String)
JTextField(String, int)
JTextField(int)
JTextField(Document, String, int)Create a JTextFieldinstance, initializing it to contain the specified text. Theintargument sets the number of columns. This is used to compute the component's preferred width and may not be the actual number of columns displayed [CHECK].void setText(String)
String getText()Set or get the text displayed by the text field.
Fine Tuning the Text Field's Appearance Method or Constructor Purpose void setEditable(boolean)
boolean isEditable()Set or get whether the user can edit the text in the text field. void setForeground(Color)
Color getForeground()Set or get the color of the text within the text field. void setBackground(Color);
Color getBackground()Set or get the background color of the text field. void setFont(Font);
Font getFont()Set or get the font used by the text field. void setHorizontalAlignment(int);
int getHorizontalAlignment()Set or get how the text is aligned horizontally within its area. You can use JTextField.LEFT,JTextField.CENTER, andJTextField.RIGHTfor arguments.
Handling Events from a Text Field Method or Constructor Purpose addActionListener(ActionListener)Provide the text field with an ActionListener. Examples that Use JTextField
This table shows the examples that useJTextFieldand where those examples are described.
Example Where Described Notes LoanCalc.javaThis page. Uses box layouts to align labels with text fields. ControlPane.java,Utilities.javaLet's Play Uses a grid bag layout to align labels with text fields. See the addParameterRowmethod inUtilities.java. Part of the BINGO player application.CustomDialog.javaHow to Make Dialogs Includes a text field whose value is checked. Part of DialogDemo (under the More Dialogs tab). EeyoreQuotes.javaHow to Use Text Components Contains several text components, including a JTextFieldand aJPasswordField.
|
|
Using the JFC/Swing Packages |