JTextField


Summary:

While creating a GUI in Java it will most likely become necessary to accept some input from the user. The JTextField is a widget which accepts textual input from a user. In the process of allowing for this input, it is important to keep in mind the usability of the interface being created. This document will illustrate how to use attributes and various methods of the JTextField to help in achieving a usable interface that accepts textual input from the user.


Where to Find It:

JTextField is a Swing component located in the javax.swing package. It is a subclass of javax.swing.text.JTextComponent and is meant to be used in the place of java.awt.TextField.


The Basics:

Implementing JTextField in its most straightforward manner is simple. Like all classes, you first need to create an instance of the JTextField class. This instance then needs to be added to a container. This is shown in the following example:

JPanel panel = new JPanel();

JTextField textField = new JTextField();

panel.add(textField);



This will add a JTextField to the JPanel with all the default settings.

Customization:

The JTextField can be customized in various ways. An instance of JTextField can be created with a specified number of columns or with default text. The default text can be used to instruct the user as to the purpose of the text field. The following example demonstrates how to create a JTextField with default text letting the user of the application know they need to input their name:

JPanel panel = new JPanel();

JTextField nameField = new JTextField(“Enter your name here.”);

panel.add(nameField);



Another method which can be called to help a user is setToolTipText. This will create text that appears when a user holds their cursor over the component for a brief amount of time.

JTextField nameField = new JTextField();

nameField.setToolTipText(“Put your name here please.”);



Though not directly attached with the JTextField, but the intention of a JTextField can be made clear with a JLabel. This also makes it somewhat simpler for a user to select the text field. Take our previous example. If we create a JLabel with the text “Name:” then a user has yet another indication of the text field that follows.

JLabel nameLabel = new JLabel(“Name:”);

panel.add(nameLabel);

panel.add(nameField);



A JTextField can also be instantiated with a given number of columns visible. This will alter the text field's preferred width and with it the way in which it is clayed out in its container.

JTextField textField = new JTextField(20);



Best Practices:

Limitations:

Things to Watch Out for When Including JTextField:

References:

JavaTM 2 Platform, Standard Edition, v 1.4.2 API Specification

http://java.sun.com/j2se/1.4.2/docs/api/index.html


HCI Models, Theories, and Frameworks

John M. Carroll



Other Helpful Resources:

How to Use Text Fields

http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html