JTextField is a lightweight component that allows the editing
of a single line of text.
For information on and examples of using text fields,
see
How to Use Text Fields
in The Java Tutorial.
JTextField is intended to be source-compatible
with java.awt.TextField where it is reasonable to do so. This
component has capabilities not found in the java.awt.TextField
class. The superclass should be consulted for additional capabilities.
JTextField has a method to establish the string used as the
command string for the action event that gets fired. The
java.awt.TextField used the text of the field as the command
string for the ActionEvent.
JTextField will use the command
string set with the setActionCommand method if not null,
otherwise it will use the text of the field as a compatibility with
java.awt.TextField.
The method setEchoChar and getEchoChar
are not provided directly to avoid a new implementation of a
pluggable look-and-feel inadvertently exposing password characters.
To provide password-like services a separate class JPasswordField
extends JTextField to provide this service with an independently
pluggable look-and-feel.
The java.awt.TextField could be monitored for changes by adding
a TextListener for TextEvent's.
In the JTextComponent based
components, changes are broadcasted from the model via a
DocumentEvent to DocumentListeners.
The DocumentEvent gives
the location of the change and the kind of change if desired.
The code fragment might look something like:
DocumentListener myListener = ??;
JTextField myArea = ??;
myArea.getDocument().addDocumentListener(myListener);
The horizontal alignment of JTextField can be set to be left
justified, leading justified, centered, right justified or trailing justified.
Right/trailing justification is useful if the required size
of the field text is smaller than the size allocated to it.
This is determined by the setHorizontalAlignment
and getHorizontalAlignment methods. The default
is to be leading justified.
How the text field consumes VK_ENTER events depends on whether the text field has any action listeners. If so, then VK_ENTER results in the listeners getting an ActionEvent, and the VK_ENTER event is consumed. This is compatible with how AWT text fields handle VK_ENTER events. If the text field has no action listeners, then as of v 1.3 the VK_ENTER event is not consumed. Instead, the bindings of ancestor components are processed, which enables the default button feature of JFC/Swing to work.
Customized fields can easily be created by extending the model and changing the default model provided. For example, the following piece of code will create a field that holds only upper case characters. It will work even if text is pasted into from the clipboard or it is altered via programmatic changes.
public class UpperCaseField extends JTextField {
public UpperCaseField(int cols) {
super(cols);
}
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return;
}
char[] upper = str.toCharArray();
for (int i = 0; i < upper.length; i++) {
upper[i] = Character.toUpperCase(upper[i]);
}
super.insertString(offs, new String(upper), a);
}
}
}
Warning
Swing is not thread safe. For more information see Swing's Threading Policy.
Warning
Serialized objects of this class will not be compatible with
future Swing releases. The current serialization support is
appropriate for short term storage or RMI between applications running
the same version of Swing. As of 1.4, support for long term storage
of all JavaBeans
has been added to the java.beans package.
Please see java..
setActionCommand, JPasswordField, addActionListener
| Modifier and Type | Class and Description |
|---|---|
| protected class | JTextField.
This class implements accessibility support for the
|
| pack-priv static class | |
| pack-priv class | |
| private static class |
| Modifier and Type | Field and Description |
|---|---|
| private Action | |
| private PropertyChangeListener | |
| private int | |
| private int | |
| private String | |
| private static final Action[] | |
| private int | |
| public static final String | notifyAction
Name of the action to send notification that the contents of the field have been accepted. |
| private static final String | |
| private BoundedRangeModel |
| Access | Constructor and Description |
|---|---|
| public | |
| public | JTextField(String
the text to be displayed, or text)nullConstructs a new |
| public | JTextField(int
the number of columns to use to calculate
the preferred width; if columns is set to zero, the
preferred width will be whatever naturally results from
the component implementation columns)Constructs a new empty |
| public | JTextField(String
the text to be displayed, or text, int nullthe number of columns to use to calculate
the preferred width; if columns is set to zero, the
preferred width will be whatever naturally results from
the component implementation columns)Constructs a new |
| public | JTextField(Document
the text storage to use; if this is doc, String null,
a default will be provided by calling the
createDefaultModel methodthe initial string to display, or text, int nullthe number of columns to use to calculate
the preferred width >= 0; if columns)columns
is set to zero, the preferred width will be whatever
naturally results from the component implementationConstructs a new |
| Modifier and Type | Method and Description |
|---|---|
| protected void | actionPropertyChanged(Action
the action, String Action associated with this textfieldthe name of the property that changed propertyName)Updates the textfield's state in response to property changes in associated action. |
| public synchronized void | addActionListener(ActionListener
the action listener to be added l)Adds the specified action listener to receive action events from this textfield. |
| protected void | configurePropertiesFromAction(Action
the a)Action from which to get the properties,
or nullSets the properties on this textfield to match those in the specified
|
| protected PropertyChangeListener | Returns: aPropertyChangeListener that is responsible for
listening for changes from the specified Action and
updating the appropriate propertiesthe textfield's action a)Creates and returns a |
| protected Document | Returns: the default model implementationCreates the default implementation of the model to be used at construction if one isn't explicitly given. |
| protected void | fireActionPerformed()
Notifies all listeners that have registered interest for notification on this event type. |
| public AccessibleContext | Returns: anAccessibleJTextField that serves as the
AccessibleContext of this JTextFieldOverrides javax. Implements javax. Gets the |
| public Action | Returns: theAction for this ActionEvent source,
or nullReturns the currently set |
| public synchronized ActionListener[] | Returns: all of theActionListeners added or an empty
array if no listeners have been addedReturns an array of all the |
| public Action[] | Returns: the command listOverrides javax. Fetches the command list for the editor. |
| public int | |
| protected int | |
| public int | Returns: the horizontal alignmentReturns the horizontal alignment of the text. |
| public BoundedRangeModel | |
| public Dimension | Returns: the dimension of this textfieldOverrides javax. Returns the preferred size |
| public int | |
| public String | Returns: the string "TextFieldUI"Overrides javax. Gets the class ID for a UI. |
| pack-priv boolean | |
| private boolean | |
| public boolean | Returns: if the parent of this textfield is aJViewPort
return false, otherwise return trueOverrides javax. Calls to |
| protected String | Returns: a string representation of thisJTextFieldOverrides javax. Returns a string representation of this |
| public void | postActionEvent()
Processes action events occurring on this textfield by
dispatching them to any registered |
| public synchronized void | removeActionListener(ActionListener
the action listener to be removed l)Removes the specified action listener so that it no longer receives action events from this textfield. |
| public void | scrollRectToVisible(Rectangle
the region to scroll r)Overrides javax. Scrolls the field left or right. |
| public void | |
| public void | |
| private void | |
| public void | setColumns(int
the number of columns >= 0 columns)Sets the number of columns in this |
| public void | setDocument(Document
the document to display/edit doc)Overrides javax. Associates the editor with a text document. |
| public void | |
| public void | |
| public void | |
| private void | writeObject(ObjectOutputStream s)
Hides javax. See |
| action | back to summary |
|---|---|
| private Action action | |
| actionPropertyChangeListener | back to summary |
|---|---|
| private PropertyChangeListener actionPropertyChangeListener | |
| columns | back to summary |
|---|---|
| private int columns | |
| columnWidth | back to summary |
|---|---|
| private int columnWidth | |
| command | back to summary |
|---|---|
| private String command | |
| defaultActions | back to summary |
|---|---|
| private static final Action[] defaultActions | |
| horizontalAlignment | back to summary |
|---|---|
| private int horizontalAlignment | |
| notifyAction | back to summary |
|---|---|
| public static final String notifyAction Name of the action to send notification that the contents of the field have been accepted. Typically this is bound to a carriage-return. | |
| uiClassID | back to summary |
|---|---|
| private static final String uiClassID Hides javax.
| |
| visibility | back to summary |
|---|---|
| private BoundedRangeModel visibility | |
| JTextField | back to summary |
|---|---|
| public JTextField() Constructs a new | |
| JTextField | back to summary |
|---|---|
| public JTextField(String text) Constructs a new
| |
| JTextField | back to summary |
|---|---|
| public JTextField(int columns) Constructs a new empty
| |
| JTextField | back to summary |
|---|---|
| public JTextField(String text, int columns) Constructs a new
| |
| JTextField | back to summary |
|---|---|
| public JTextField(Document doc, String text, int columns) Constructs a new
| |
| actionPropertyChanged | back to summary |
|---|---|
| protected void actionPropertyChanged(Action action, String propertyName) Updates the textfield's state in response to property changes in
associated action. This method is invoked from the
Refer to the table at
Swing Components Supporting
| |
| addActionListener | back to summary |
|---|---|
| public synchronized void addActionListener(ActionListener l) Adds the specified action listener to receive action events from this textfield.
| |
| configurePropertiesFromAction | back to summary |
|---|---|
| protected void configurePropertiesFromAction(Action a) Sets the properties on this textfield to match those in the specified
| |
| createActionPropertyChangeListener | back to summary |
|---|---|
| protected PropertyChangeListener createActionPropertyChangeListener(Action a) Creates and returns a Warning If you subclass this do not create an anonymous
inner class. If you do the lifetime of the textfield will be tied to
that of the
| |
| createDefaultModel | back to summary |
|---|---|
| protected Document createDefaultModel() Creates the default implementation of the model
to be used at construction if one isn't explicitly
given. An instance of
| |
| fireActionPerformed | back to summary |
|---|---|
| protected void fireActionPerformed() Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created. The listener list is processed in last to first order.
| |
| getAccessibleContext | back to summary |
|---|---|
| public AccessibleContext getAccessibleContext() Overrides javax. Implements javax. Gets the
| |
| getAction | back to summary |
|---|---|
| public Action getAction() Returns the currently set | |
| getActionListeners | back to summary |
|---|---|
| public synchronized ActionListener[] getActionListeners() Returns an array of all the
| |
| getActions | back to summary |
|---|---|
| public Action[] getActions() Overrides javax. Fetches the command list for the editor. This is the list of commands supported by the plugged-in UI augmented by the collection of commands that the editor itself supports. These are useful for binding to events, such as in a keymap.
| |
| getColumns | back to summary |
|---|---|
| public int getColumns() Returns the number of columns in this
| |
| getColumnWidth | back to summary |
|---|---|
| protected int getColumnWidth() Returns the column width. The meaning of what a column is can be considered a fairly weak notion for some fonts. This method is used to define the width of a column. By default this is defined to be the width of the character m for the font used. This method can be redefined to be some alternative amount
| |
| getHorizontalAlignment | back to summary |
|---|---|
| public int getHorizontalAlignment() Returns the horizontal alignment of the text. Valid keys are:
| |
| getHorizontalVisibility | back to summary |
|---|---|
| public BoundedRangeModel getHorizontalVisibility() Gets the visibility of the text field. This can be adjusted to change the location of the visible area if the size of the field is greater than the area that was allocated to the field.
The fields look-and-feel implementation manages
the values of the minimum, maximum, and extent
properties on the
| |
| getPreferredSize | back to summary |
|---|---|
| public Dimension getPreferredSize() Overrides javax. Returns the preferred size
| |
| getScrollOffset | back to summary |
|---|---|
| public int getScrollOffset() Gets the scroll offset, in pixels.
| |
| getUIClassID | back to summary |
|---|---|
| public String getUIClassID() Overrides javax. Gets the class ID for a UI.
| |
| hasActionListener | back to summary |
|---|---|
| pack-priv boolean hasActionListener() Returns true if the receiver has an | |
| isListener | back to summary |
|---|---|
| private boolean isListener(Class<?> c, ActionListener a) | |
| isValidateRoot | back to summary |
|---|---|
| public boolean isValidateRoot() Overrides javax. Calls to
| |
| paramString | back to summary |
|---|---|
| protected String paramString() Overrides javax. Returns a string representation of this
| |
| postActionEvent | back to summary |
|---|---|
| public void postActionEvent() Processes action events occurring on this textfield by
dispatching them to any registered | |
| removeActionListener | back to summary |
|---|---|
| public synchronized void removeActionListener(ActionListener l) Removes the specified action listener so that it no longer receives action events from this textfield.
| |
| scrollRectToVisible | back to summary |
|---|---|
| public void scrollRectToVisible(Rectangle r) Overrides javax. Scrolls the field left or right.
| |
| setAction | back to summary |
|---|---|
| public void setAction(Action a) Sets the
Setting the
This method uses three other methods to set
and help track the
| |
| setActionCommand | back to summary |
|---|---|
| public void setActionCommand(String command) Sets the command string used for action events.
| |
| setActionCommandFromAction | back to summary |
|---|---|
| private void setActionCommandFromAction(Action action) | |
| setColumns | back to summary |
|---|---|
| public void setColumns(int columns) Sets the number of columns in this
| |
| setDocument | back to summary |
|---|---|
| public void setDocument(Document doc) Overrides javax. Associates the editor with a text document. The currently registered factory is used to build a view for the document, which gets displayed by the editor after revalidation. A PropertyChange event ("document") is propagated to each listener.
| |
| setFont | back to summary |
|---|---|
| public void setFont(Font f) Overrides javax. Sets the current font. This removes cached row height and column
width so the new font will be reflected.
| |
| setHorizontalAlignment | back to summary |
|---|---|
| public void setHorizontalAlignment(int alignment) Sets the horizontal alignment of the text. Valid keys are:
invalidate and repaint are called when the
alignment is set,
and a PropertyChange event ("horizontalAlignment") is fired.
| |
| setScrollOffset | back to summary |
|---|---|
| public void setScrollOffset(int scrollOffset) Sets the scroll offset, in pixels.
| |
| writeObject | back to summary |
|---|---|
| private void writeObject(ObjectOutputStream s) throws IOException Hides javax. See
| |
JTextField class. It provides an implementation of the
Java Accessibility API appropriate to text field user-interface
elements.Warning
Serialized objects of this class will not be compatible with
future Swing releases. The current serialization support is
appropriate for short term storage or RMI between applications running
the same version of Swing. As of 1.4, support for long term storage
of all JavaBeans
has been added to the java.beans package.
Please see java..
| Access | Constructor and Description |
|---|---|
| protected |
| Modifier and Type | Method and Description |
|---|---|
| public AccessibleStateSet | Returns: an instance of AccessibleStateSet describing the states of the objectOverrides javax. Gets the state set of this object. |
| AccessibleJTextField | back to summary |
|---|---|
| protected AccessibleJTextField() Constructs an | |
| getAccessibleStateSet | back to summary |
|---|---|
| public AccessibleStateSet getAccessibleStateSet() Overrides javax. Gets the state set of this object.
| |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| public void | actionPerformed(ActionEvent e)
Implements java. Invoked when an action occurs. |
| public boolean | isEnabled()
Overrides javax. Implements javax. Returns true if the action is enabled. |
| NotifyAction | back to summary |
|---|---|
| pack-priv NotifyAction() | |
| actionPerformed | back to summary |
|---|---|
| public void actionPerformed(ActionEvent e) Implements java. Doc from java. Invoked when an action occurs. | |
| isEnabled | back to summary |
|---|---|
| public boolean isEnabled() Overrides javax. Implements javax. Doc from javax. Returns true if the action is enabled. | |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| public void | stateChanged(ChangeEvent e)
Implements javax. Invoked when the target of the listener has changed its state. |
| ScrollRepainter | back to summary |
|---|---|
| pack-priv ScrollRepainter() | |
| stateChanged | back to summary |
|---|---|
| public void stateChanged(ChangeEvent e) Implements javax. Doc from javax. Invoked when the target of the listener has changed its state. | |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| protected void | actionPropertyChanged(JTextField textField, Action action, PropertyChangeEvent e)
Implements abstract javax. Invoked when a property changes on the Action and the target still exists. |
| TextFieldActionPropertyChangeListener | back to summary |
|---|---|
| pack-priv TextFieldActionPropertyChangeListener(JTextField tf, Action a) | |
| actionPropertyChanged | back to summary |
|---|---|
| protected void actionPropertyChanged(JTextField textField, Action action, PropertyChangeEvent e) Implements abstract javax. Doc from javax. Invoked when a property changes on the Action and the target still exists. | |