- All Implemented Interfaces:
ImageObserver
,MenuContainer
,Serializable
,Accessible
,Scrollable
,SwingConstants
- Direct Known Subclasses:
TimeTextField
,WholeNumbTextField
onAccepted()
when text is valid and
either the focus changes or the text was changed by calling
setText(String)
, or when the user presses a
key such as the "Enter"/"Return" key. The method
handleError()
is called
when input verification fails after the keyboard
focus is lost, but not after setText(String)
is called
and input verification fails.
The default behavior for handleError()
(if
there is an error) simply restores the previous value and (if
possible) keeps the keyboard focus on the text field.
To configure this text field to verify its contents, one must
call the method setInputVerifier(InputVerifier)
.
To restrict the input to particular characters, this text field's
document should be a subclass of AbstractDocument
and the
document's
AbstractDocument.setDocumentFilter(javax.swing.text.DocumentFilter)
should be called. If a document filter is used, illegal characters
must not be included in a string passed to
JTextComponent.setText(String)
as the the new text will be
ignored. Characters that will be illegal once a document filter
is installed can be passed to a contructor, but doing this can
result in unexpected behavior if JTextComponent.getText()
is
called and that text is reused in calls to
JTextComponent.setText(String)
. Consequently, it is advisable
for strings passed to the constructor to contain only characters
that will be allowable after the document filter is installed.
- See Also:
-
Nested Class Summary
Nested ClassesNested classes/interfaces inherited from class javax.swing.JTextField
JTextField.AccessibleJTextField
Nested classes/interfaces inherited from class javax.swing.text.JTextComponent
JTextComponent.AccessibleJTextComponent, JTextComponent.DropLocation, JTextComponent.KeyBinding
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
-
Field Summary
Fields inherited from class javax.swing.JTextField
notifyAction
Fields inherited from class javax.swing.text.JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
Fields inherited from class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
-
Constructor Summary
ConstructorsConstructorDescriptionClass constructor.VTextField
(int ncols) Class constructor specifying the field size..VTextField
(String text) Class constructor giving an initial string.VTextField
(String text, int ncols) Class constructor giving an initial string and field size.VTextField
(Document doc, String text, int ncols) Class constructor for a document model, initial string and field size. -
Method Summary
Modifier and TypeMethodDescriptionprotected void
boolean
Determine if empty text fields are allowed.Get the text field.protected boolean
Handle an error.protected void
Accept input.void
removeActionListener
(ActionListener listener) void
setAllowEmptyTextField
(boolean value) Set whether or not empty text fields are allowed.void
Set the error policyvoid
setInputVerifier
(InputVerifier verifier) Set the input verifier.void
Set the text field if the field would be accepted.Methods inherited from class javax.swing.JTextField
actionPropertyChanged, addActionListener, configurePropertiesFromAction, createActionPropertyChangeListener, createDefaultModel, getAccessibleContext, getAction, getActionListeners, getActions, getColumns, getColumnWidth, getHorizontalAlignment, getHorizontalVisibility, getPreferredSize, getScrollOffset, getUIClassID, isValidateRoot, paramString, postActionEvent, scrollRectToVisible, setAction, setActionCommand, setColumns, setDocument, setFont, setHorizontalAlignment, setScrollOffset
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropLocation, getDropMode, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getPrintable, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, modelToView2D, moveCaretPosition, paste, print, print, print, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, restoreComposedText, saveComposedText, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setDropMode, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setUI, updateUI, viewToModel, viewToModel2D, write
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setForeground, setInheritsPopupMenu, setInputMap, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
Constructor Details
-
VTextField
public VTextField(int ncols) Class constructor specifying the field size..- Parameters:
ncols
- the number of columns in the text field.
-
VTextField
public VTextField()Class constructor. -
VTextField
Class constructor giving an initial string.- Parameters:
text
- the initial text
-
VTextField
Class constructor giving an initial string and field size.- Parameters:
text
- the initial textncols
- the number of columns in the text field.
-
VTextField
Class constructor for a document model, initial string and field size.- Parameters:
doc
- the document modeltext
- the initial textncols
- the number of columns in the text field.
-
-
Method Details
-
setErrorPolicy
Set the error policy- Parameters:
ep
- the error policy- Throws:
IllegalStateException
- empty text fields allowed, but the argument was ErrorPolicy.CLEAR_VALUE- See Also:
-
handleError
protected boolean handleError()Handle an error. If this method is overridden it should return true only if it has attempted to correct the error. Correcting the error will typically require callingsetText(String)
with the corrected value (this method will check its argument).- Returns:
- return true if a value has been provided; false to keep the old value.
- See Also:
-
onAccepted
Accept input. This method will be called when input is accepted, either by terminating the input with the "Enter" or "Return" key, or by changing the focus to another component in this application. Note that selecting a window in a separate application may not trigger this method.The default method does nothing, but may be overridden to perform some operation when the value of the text field changes to a new accepted value. During error correction, this may happen multiple times. It can also happen if the method
setText(String)
is called. While this method can throw an exception, it is called in such a way that the exception will normally be caught by this class' methods and processed silently if at all.When an instance of this class is constructed and the text field is empty, an initial call to this method is suppressed.
- Throws:
Exception
- an error occurred
-
setText
Set the text field if the field would be accepted. As a special case, whengetAllowEmptyTextField()
returnstrue
the text may be set to an empty string in order to clear the field. Otherwise, if the input is valid,onAccepted()
will be called, but if the text is not valid, the existing value will be preserved. The methodonAccepted()
must handle the case where the text field is empty whengetAllowEmptyTextField()
returnstrue
.If the input is not valid, as determined by the value of
getAllowEmptyTextField()
or by an input verifier, the previous value is preserved.While the method
onAccepted()
is being called, this method simply sets the text with no constraints on its value. In this case, the caller must ensure that the argument is a valid one.- Overrides:
setText
in classJTextComponent
- Parameters:
str
- the value for the string.- Throws:
IllegalArgumentException
- The input is not valid
-
setAllowEmptyTextField
Set whether or not empty text fields are allowed. The default setting istrue
. This method affects how text is accepted. Fields may be temporarily empty while editing them. In addition, a field may be empty when an instance of this class is constructed, in which caseonAccepted()
will not be called until the text is changed.- Parameters:
value
- true if empty text fields are allowed; false otherwise- Throws:
IllegalStateException
-
getAllowEmptyTextField
public boolean getAllowEmptyTextField()Determine if empty text fields are allowed.- Returns:
- true if empty text fields are allowed; false otherwise.
-
getValidatedText
Get the text field. This does a validity test and if the text is not valid, the old value is used. If handleError is overridden, the value may be corrected if not valid.The method
onAccepted()
will be called if the input is valid. If this method is called when the text field is empty and whengetAllowEmptyTextField()
returnsfalse
,handleError()
will be called.- Returns:
- the text displayed if it is valid; otherwise the text before the last editing operation.
-
fireActionPerformed
protected void fireActionPerformed()- Overrides:
fireActionPerformed
in classJTextField
-
removeActionListener
- Overrides:
removeActionListener
in classJTextField
-
setInputVerifier
Set the input verifier. This should be used to determine the validity of the text field's contents. An internal input verifier is actually used and that input verifier uses the one set by this method, with the internal verifier handling some aspects of a change of focus.- Overrides:
setInputVerifier
in classJComponent
- Parameters:
verifier
- the input verifier; null if the input should always be accepted.
-