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.
For the keyboard keys used by this component in the standard Look and
Feel (L&F) renditions, see the
JTextField
key assignments.
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:
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 JavaBeansTM
has been added to the java.beans
package.
Please see {@link java.beans.XMLEncoder}.
Attribute Summary | ||
---|---|---|
Attribute | Type | Description |
action | Action | Sets the Action for the ActionEvent source.
|
actioncommand | <text> | Sets the command string used for action events. |
actionmap | ActionMap | Sets the ActionMap to am . |
alignmentx | <float> | Sets the the vertical alignment. |
alignmenty | <float> | Sets the the horizontal alignment. |
autoscrolls | <boolean> | Sets the autoscrolls property.
|
background | <color> | Sets the background color of this component. |
border | Border | Sets the border of this component. |
bounds | <rectangle> | Moves and resizes this component to conform to the new
bounding rectangle r . |
caret | Caret | Sets the caret to be used. |
caretcolor | <color> | Sets the current color used to render the caret. |
caretposition | <int> | Sets the position of the text insertion caret for the
TextComponent . |
columns | <int> | Sets the number of columns in this TextField ,
and then invalidate the layout. |
componentorientation | ComponentOrientation | |
cursor | <cursor> | Sets the cursor image to the specified cursor. |
debuggraphicsoptions | <int> | Enables or disables diagnostic information about every graphics operation performed within the component or one of its children. |
defaultlocale | <locale> | Sets the default locale used to initialize each JComponent's locale property upon creation. |
disabledtextcolor | <color> | Sets the current color used to render the disabled text. |
document | Document | Associates the editor with a text document. |
doublebuffered | <boolean> | Sets whether the this component should use a buffer to paint. |
dragenabled | <boolean> | Sets the dragEnabled property,
which must be true to enable
automatic drag handling (the first part of drag and drop)
on this component.
|
droptarget | DropTarget | Associate a DropTarget with this component.
|
editable | <boolean> | Sets the specified boolean to indicate whether or not this
TextComponent should be editable.
|
enabled | <boolean> | Sets whether or not this component is enabled. |
focusable | <boolean> | Sets the focusable state of this Component to the specified value. |
focusaccelerator | <char> | Sets the key accelerator that will cause the receiving text component to get the focus. |
focuscycleroot | <boolean> | Sets whether this Container is the root of a focus traversal cycle. |
focustraversalkeysenabled | <boolean> | Sets whether focus traversal keys are enabled for this Component. |
focustraversalpolicy | FocusTraversalPolicy | Sets the focus traversal policy that will manage keyboard traversal of this Container's children, if this Container is a focus cycle root. |
font | <font> | Sets the current font. |
foreground | <color> | Sets the foreground color of this component. |
highlighter | Highlighter | Sets the highlighter to be used. |
horizontalalignment | <int> | Sets the horizontal alignment of the text. |
ignorerepaint | <boolean> | Sets whether or not paint messages received from the operating system should be ignored. |
inputverifier | InputVerifier | Sets the input verifier for this component. |
keymap | Keymap | Sets the keymap to use for binding events to actions. |
layout | LayoutManager | Sets the layout manager for this container. |
locale | <locale> | Sets the locale of this component. |
location | <point> | Moves this component to a new location. |
margin | <insets> | Sets margin space between the text component's border and its text. |
maximumsize | <dimension> | Sets the maximum size of this component to a constant value. |
minimumsize | <dimension> | Sets the minimum size of this component to a constant value. |
name | <text> | Sets the name of the component to the specified string. |
navigationfilter | NavigationFilter | Sets the NavigationFilter . |
nextfocusablecomponent | Component | Overrides the default FocusTraversalPolicy for this
JComponent 's focus traversal cycle by unconditionally
setting the specified Component as the next
Component in the cycle, and this JComponent
as the specified Component 's previous
Component in the cycle. |
opaque | <boolean> | If true the component paints every pixel within its bounds. |
preferredsize | <dimension> | Sets the preferred size of this component. |
requestfocusenabled | <boolean> | Provides a hint as to whether or not this JComponent
should get focus. |
scrolloffset | <int> | Sets the scroll offset, in pixels. |
selectedtextcolor | <color> | Sets the current color used to render the selected text. |
selectioncolor | <color> | Sets the current color used to render the selection. |
selectionend | <int> | Sets the selection end to the specified position. |
selectionstart | <int> | Sets the selection start to the specified position. |
size | <dimension> | Resizes this component so that it has width d.width
and height d.height . |
text | <text> | Sets the text of this TextComponent
to the specified text. |
tooltiptext | <text> | Registers the text to display in a tool tip. |
transferhandler | TransferHandler | Sets the transferHandler property,
which is null if the component does
not support data transfer operations.
|
ui | TextUI | Sets the user-interface factory for this text-oriented editor. |
verifyinputwhenfocustarget | <boolean> | Sets the value to indicate whether input verifier for the current focus owner will be called before this component requests focus. |
visible | <boolean> | Makes the component visible or invisible. |