javax.swing
public class: JFormattedTextField [javadoc |
source]
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.text.JTextComponent
javax.swing.JTextField
javax.swing.JFormattedTextField
All Implemented Interfaces:
SwingConstants, Scrollable, Accessible, HasGetTransferHandler, Serializable, MenuContainer, ImageObserver
JFormattedTextField
extends
JTextField
adding
support for formatting arbitrary values, as well as retrieving a particular
object once the user has edited the text. The following illustrates
configuring a
JFormattedTextField
to edit dates:
JFormattedTextField ftf = new JFormattedTextField();
ftf.setValue(new Date());
Once a JFormattedTextField
has been created, you can
listen for editing changes by way of adding
a PropertyChangeListener
and listening for
PropertyChangeEvent
s with the property name value
.
JFormattedTextField
allows
configuring what action should be taken when focus is lost. The possible
configurations are:
Value | Description |
JFormattedTextField.REVERT
| Revert the display to match that of getValue ,
possibly losing the current edit.
|
JFormattedTextField.COMMIT
| Commits the current value. If the value being edited
isn't considered a legal value by the
AbstractFormatter that is, a
ParseException is thrown, then the value
will not change, and then edited value will persist.
|
JFormattedTextField.COMMIT_OR_REVERT
| Similar to COMMIT , but if the value isn't
legal, behave like REVERT .
|
JFormattedTextField.PERSIST
| Do nothing, don't obtain a new
AbstractFormatter , and don't update the value.
|
The default is
JFormattedTextField.COMMIT_OR_REVERT
,
refer to
#setFocusLostBehavior for more information on this.
JFormattedTextField
allows the focus to leave, even if
the currently edited value is invalid. To lock the focus down while the
JFormattedTextField
is an invalid edit state
you can attach an InputVerifier
. The following code snippet
shows a potential implementation of such an InputVerifier
:
public class FormattedTextFieldVerifier extends InputVerifier {
public boolean verify(JComponent input) {
if (input instanceof JFormattedTextField) {
JFormattedTextField ftf = (JFormattedTextField)input;
AbstractFormatter formatter = ftf.getFormatter();
if (formatter != null) {
String text = ftf.getText();
try {
formatter.stringToValue(text);
return true;
} catch (ParseException pe) {
return false;
}
}
}
return true;
}
public boolean shouldYieldFocus(JComponent input) {
return verify(input);
}
}
Alternatively, you could invoke commitEdit
, which would also
commit the value.
JFormattedTextField
does not do the formatting it self,
rather formatting is done through an instance of
JFormattedTextField.AbstractFormatter
which is obtained from
an instance of JFormattedTextField.AbstractFormatterFactory
.
Instances of JFormattedTextField.AbstractFormatter
are
notified when they become active by way of the
install
method, at which point the
JFormattedTextField.AbstractFormatter
can install whatever
it needs to, typically a DocumentFilter
. Similarly when
JFormattedTextField
no longer
needs the AbstractFormatter
, it will invoke
uninstall
.
JFormattedTextField
typically
queries the AbstractFormatterFactory
for an
AbstractFormat
when it gains or loses focus. Although this
can change based on the focus lost policy. If the focus lost
policy is JFormattedTextField.PERSIST
and the JFormattedTextField
has been edited, the
AbstractFormatterFactory
will not be queried until the
value has been commited. Similarly if the focus lost policy is
JFormattedTextField.COMMIT
and an exception
is thrown from stringToValue
, the
AbstractFormatterFactory
will not be querired when focus is
lost or gained.
JFormattedTextField.AbstractFormatter
is also responsible for determining when values are commited to
the JFormattedTextField
. Some
JFormattedTextField.AbstractFormatter
s will make new values
available on every edit, and others will never commit the value. You can
force the current value to be obtained
from the current JFormattedTextField.AbstractFormatter
by way of invoking commitEdit
. commitEdit
will
be invoked whenever return is pressed in the
JFormattedTextField
.
If an AbstractFormatterFactory
has not been explicitly
set, one will be set based on the Class
of the value type after
setValue
has been invoked (assuming value is non-null).
For example, in the following code an appropriate
AbstractFormatterFactory
and AbstractFormatter
will be created to handle formatting of numbers:
JFormattedTextField tf = new JFormattedTextField();
tf.setValue(new Number(100));
Warning: As the AbstractFormatter
will
typically install a DocumentFilter
on the
Document
, and a NavigationFilter
on the
JFormattedTextField
you should not install your own. If you do,
you are likely to see odd behavior in that the editing policy of the
AbstractFormatter
will not be enforced.
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 JavaBeansTM
has been added to the java.beans
package.
Please see java.beans.XMLEncoder .
Nested Class Summary: |
---|
abstract public static class | JFormattedTextField.AbstractFormatterFactory | Instances of AbstractFormatterFactory are used by
JFormattedTextField to obtain instances of
AbstractFormatter which in turn are used to format values.
AbstractFormatterFactory can return different
AbstractFormatter s based on the state of the
JFormattedTextField , perhaps returning different
AbstractFormatter s when the
JFormattedTextField has focus vs when it
doesn't have focus. |
abstract public static class | JFormattedTextField.AbstractFormatter | Instances of AbstractFormatter are used by
JFormattedTextField to handle the conversion both
from an Object to a String, and back from a String to an Object.
AbstractFormatter s can also enfore editing policies,
or navigation policies, or manipulate the
JFormattedTextField in any way it sees fit to
enforce the desired policy.
An AbstractFormatter can only be active in
one JFormattedTextField at a time.
JFormattedTextField invokes
install when it is ready to use it followed
by uninstall when done. Subclasses
that wish to install additional state should override
install and message super appropriately.
Subclasses must override the conversion methods
stringToValue and valueToString . Optionally
they can override getActions ,
getNavigationFilter and getDocumentFilter
to restrict the JFormattedTextField in a particular
way.
Subclasses that allow the JFormattedTextField to be in
a temporarily invalid state should invoke setEditValid
at the appropriate times. |
static class | JFormattedTextField.CommitAction | Used to commit the edit. This extends JTextField.NotifyAction
so that isEnabled is true while a JFormattedTextField
has focus, and extends actionPerformed to invoke
commitEdit. |
Field Summary |
---|
public static final int | COMMIT | Constant identifying that when focus is lost,
commitEdit should be invoked. If in commiting the
new value a ParseException is thrown, the invalid
value will remain. |
public static final int | COMMIT_OR_REVERT | Constant identifying that when focus is lost,
commitEdit should be invoked. If in commiting the new
value a ParseException is thrown, the value will be
reverted. |
public static final int | REVERT | Constant identifying that when focus is lost, editing value should
be reverted to current value set on the
JFormattedTextField . |
public static final int | PERSIST | Constant identifying that when focus is lost, the edited value
should be left. |
Fields inherited from javax.swing.JComponent: |
---|
DEBUG_GRAPHICS_LOADED, ui, listenerList, paintingChild, WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_IN_FOCUSED_WINDOW, UNDEFINED_CONDITION, TOOL_TIP_TEXT_KEY, focusController, accessibleContext |
Fields inherited from java.awt.Component: |
---|
peer, parent, appContext, x, y, width, height, foreground, background, font, peerFont, cursor, locale, bufferStrategy, ignoreRepaint, visible, enabled, dropTarget, popups, focusTraversalKeys, LOCK, minSize, minSizeSet, prefSize, prefSizeSet, maxSize, maxSizeSet, componentOrientation, newEventsOnly, componentListener, focusListener, hierarchyListener, hierarchyBoundsListener, keyListener, mouseListener, mouseMotionListener, mouseWheelListener, inputMethodListener, windowClosingException, actionListenerK, adjustmentListenerK, componentListenerK, containerListenerK, focusListenerK, itemListenerK, keyListenerK, mouseListenerK, mouseMotionListenerK, mouseWheelListenerK, textListenerK, ownedWindowK, windowListenerK, inputMethodListenerK, hierarchyListenerK, hierarchyBoundsListenerK, windowStateListenerK, windowFocusListenerK, eventMask, isInc, incRate, TOP_ALIGNMENT, CENTER_ALIGNMENT, BOTTOM_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, isPacked, backgroundEraseDisabled, eventCache, accessibleContext |
Constructor: |
public JFormattedTextField() {
super();
enableEvents(AWTEvent.FOCUS_EVENT_MASK);
setFocusLostBehavior(COMMIT_OR_REVERT);
}
Creates a JFormattedTextField with no
AbstractFormatterFactory . Use setMask or
setFormatterFactory to configure the
JFormattedTextField to edit a particular type of
value. |
public JFormattedTextField(Object value) {
this();
setValue(value);
}
Creates a JFormattedTextField with the specified value. This will
create an AbstractFormatterFactory based on the
type of value . Parameters:
value - Initial value for the JFormattedTextField
|
public JFormattedTextField(Format format) {
this();
setFormatterFactory(getDefaultFormatterFactory(format));
}
Creates a JFormattedTextField . format is
wrapped in an appropriate AbstractFormatter which is
then wrapped in an AbstractFormatterFactory . Parameters:
format - Format used to look up an AbstractFormatter
|
public JFormattedTextField(AbstractFormatter formatter) {
this(new DefaultFormatterFactory(formatter));
}
Creates a JFormattedTextField with the specified
AbstractFormatter . The AbstractFormatter
is placed in an AbstractFormatterFactory . Parameters:
formatter - AbstractFormatter to use for formatting.
|
public JFormattedTextField(AbstractFormatterFactory factory) {
this();
setFormatterFactory(factory);
}
Creates a JFormattedTextField with the specified
AbstractFormatterFactory . Parameters:
factory - AbstractFormatterFactory used for formatting.
|
public JFormattedTextField(AbstractFormatterFactory factory,
Object currentValue) {
this(currentValue);
setFormatterFactory(factory);
}
Creates a JFormattedTextField with the specified
AbstractFormatterFactory and initial value. Parameters:
factory - AbstractFormatterFactory used for
formatting.
currentValue - Initial value to use
|
Method from javax.swing.JFormattedTextField Summary: |
---|
commitEdit, getActions, getFocusLostBehavior, getFormatter, getFormatterFactory, getUIClassID, getValue, invalidEdit, isEditValid, processFocusEvent, processInputMethodEvent, setDocument, setFocusLostBehavior, setFormatter, setFormatterFactory, setValue |
Methods from javax.swing.JTextField: |
---|
actionPropertyChanged, addActionListener, configurePropertiesFromAction, createActionPropertyChangeListener, createDefaultModel, fireActionPerformed, getAccessibleContext, getAction, getActionListeners, getActions, getColumnWidth, getColumns, getHorizontalAlignment, getHorizontalVisibility, getPreferredSize, getScrollOffset, getUIClassID, hasActionListener, isValidateRoot, paramString, postActionEvent, removeActionListener, scrollRectToVisible, setAction, setActionCommand, setColumns, setDocument, setFont, setHorizontalAlignment, setScrollOffset |
Methods from javax.swing.text.JTextComponent: |
---|
addCaretListener, addInputMethodListener, addKeymap, composedTextExists, copy, cut, dropLocationForPoint, fireCaretUpdate, getAccessibleContext, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropLocation, getDropMode, getFocusAccelerator, getFocusedComponent, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getPrintable, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paramString, paste, print, print, print, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, restoreComposedText, saveComposedText, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDocument, setDragEnabled, setDropLocation, setDropMode, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setText, setUI, updateInputMap, updateUI, viewToModel, write |
Methods from javax.swing.JComponent: |
---|
_paintImmediately, addAncestorListener, addNotify, addVetoableChangeListener, alwaysOnTop, checkIfChildObscuredBySibling, clientPropertyChanged, compWriteObjectNotify, componentInputMapChanged, computeVisibleRect, computeVisibleRect, contains, createToolTip, disable, dndDone, dropLocationForPoint, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getCreatedDoubleBuffer, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getGraphicsInvoked, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getManagingFocusBackwardTraversalKeys, getManagingFocusForwardTraversalKeys, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getWriteObjCounter, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPainting, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintForceDoubleBuffered, paintImmediately, paintImmediately, paintToOffscreen, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyBindings, processKeyBindingsForAllComponents, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, rectangleIsObscured, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, safelyGetGraphics, safelyGetGraphics, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setCreatedDoubleBuffer, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setDropLocation, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPaintingChild, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setUIProperty, setVerifyInputWhenFocusTarget, setVisible, setWriteObjCounter, shouldDebugGraphics, superProcessMouseMotionEvent, unregisterKeyboardAction, update, updateUI |
Methods from java.awt.Container: |
---|
add, add, add, add, add, addContainerListener, addImpl, addNotify, addPropertyChangeListener, addPropertyChangeListener, adjustDecendantsOnParent, adjustDescendants, adjustListeningChildren, applyComponentOrientation, areFocusTraversalKeysSet, canContainFocusOwner, checkGD, clearCurrentFocusCycleRootOnHide, clearMostRecentFocusOwnerOnHide, containsFocus, countComponents, countHierarchyMembers, createChildHierarchyEvents, createHierarchyEvents, decreaseComponentCount, deliverEvent, dispatchEventImpl, dispatchEventToSelf, doLayout, eventEnabled, findComponentAt, findComponentAt, findComponentAt, findComponentAtImpl, getAccessibleAt, getAccessibleChild, getAccessibleChildrenCount, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponentZOrder, getComponents, getComponentsSync, getComponents_NoClientCode, getContainerListeners, getDropTargetEventTarget, getFocusTraversalKeys, getFocusTraversalPolicy, getHeavyweightContainer, getInsets, getLayout, getListeners, getMaximumSize, getMinimumSize, getMouseEventTarget, getMousePosition, getOpaqueShape, getPreferredSize, getTraversalRoot, hasHeavyweightDescendants, hasLightweightDescendants, increaseComponentCount, initializeFocusTraversalKeys, insets, invalidate, invalidateParent, invalidateTree, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, isRecursivelyVisibleUpToHeavyweightContainer, isSameOrAncestorOf, isValidateRoot, layout, lightweightPaint, lightweightPrint, list, list, locate, minimumSize, mixOnHiding, mixOnReshaping, mixOnShowing, mixOnValidating, mixOnZOrderChanging, numListening, paint, paintComponents, paintHeavyweightComponents, paramString, postProcessKeyEvent, postsOldMouseEvents, preProcessKeyEvent, preferredSize, print, printComponents, printHeavyweightComponents, processContainerEvent, processEvent, proxyEnableEvents, recursiveApplyCurrentShape, recursiveApplyCurrentShape, recursiveApplyCurrentShape, recursiveSubtractAndApplyShape, recursiveSubtractAndApplyShape, recursiveSubtractAndApplyShape, remove, remove, removeAll, removeContainerListener, removeNotify, setComponentZOrder, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, setLayout, transferFocusDownCycle, update, updateGraphicsData, validate, validateTree, validateUnconditionally |
Methods from java.awt.Component: |
---|
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, adjustListeningChildrenOnParent, applyComponentOrientation, applyCompoundShape, applyCurrentShape, areBoundsValid, areFocusTraversalKeysSet, areInputMethodsEnabled, autoProcessMouseWheel, bounds, canBeFocusOwner, canBeFocusOwnerRecursively, checkGD, checkImage, checkImage, checkTreeLock, checkWindowClosingException, clearCurrentFocusCycleRootOnHide, clearMostRecentFocusOwnerOnHide, coalesceEvents, constructComponentName, contains, contains, containsFocus, countHierarchyMembers, createBufferStrategy, createBufferStrategy, createHierarchyEvents, createImage, createImage, createVolatileImage, createVolatileImage, deliverEvent, disable, disableEvents, dispatchEvent, dispatchEventImpl, dispatchMouseWheelToAncestor, doLayout, enable, enable, enableEvents, enableInputMethods, eventEnabled, eventTypeEnabled, findUnderMouseInWindow, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAccessControlContext, getAccessibleContext, getAccessibleIndexInParent, getAccessibleStateSet, getAlignmentX, getAlignmentY, getBackBuffer, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getBoundsOp, getBufferStrategy, getColorModel, getComponentAt, getComponentAt, getComponentListeners, getComponentOrientation, getContainer, getContainingWindow, getCursor, getCursor_NoClientCode, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeys, getFocusTraversalKeysEnabled, getFocusTraversalKeys_NoIDCheck, getFont, getFontMetrics, getFont_NoClientCode, getForeground, getGraphics, getGraphicsConfiguration, getGraphicsConfiguration_NoClientCode, getGraphics_NoClientCode, getHWPeerAboveMe, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getListeners, getLocale, getLocation, getLocation, getLocationOnScreen, getLocationOnScreen_NoTreeLock, getLocationOnWindow, getMaximumSize, getMinimumSize, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getNativeContainer, getNextFocusCandidate, getNormalShape, getObjectLock, getOpaqueShape, getParent, getParent_NoClientCode, getPeer, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getSiblingIndexAbove, getSiblingIndexBelow, getSize, getSize, getToolkit, getToolkitImpl, getTraversalRoot, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, initializeFocusTraversalKeys, inside, invalidate, invalidateIfValid, invalidateParent, isAutoFocusTransferOnDisposal, isBackgroundSet, isCoalescingEnabled, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isEnabledImpl, isFocusCycleRoot, isFocusOwner, isFocusTraversable, isFocusTraversableOverridden, isFocusable, isFontSet, isForegroundSet, isInstanceOf, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isMixingNeeded, isNonOpaqueForMixing, isOpaque, isPreferredSizeSet, isRecursivelyVisible, isSameOrAncestorOf, isShowing, isValid, isVisible, isVisible_NoClientCode, keyDown, keyUp, layout, lightweightPaint, lightweightPrint, list, list, list, list, list, locate, location, lostFocus, minimumSize, mixOnHiding, mixOnReshaping, mixOnShowing, mixOnValidating, mixOnZOrderChanging, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, numListening, paint, paintAll, paintHeavyweightComponents, paramString, pointRelativeToComponent, postEvent, postsOldMouseEvents, preferredSize, prepareImage, prepareImage, print, printAll, printHeavyweightComponents, processComponentEvent, processEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, relocateComponent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocus, requestFocus, requestFocus, requestFocusHelper, requestFocusHelper, requestFocusInWindow, requestFocusInWindow, requestFocusInWindow, requestFocusInWindow, reshape, resize, resize, revalidate, setAutoFocusTransferOnDisposal, setBackground, setBounds, setBounds, setBoundsOp, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusTraversalKeys, setFocusTraversalKeysEnabled, setFocusTraversalKeys_NoIDCheck, setFocusable, setFont, setForeground, setGraphicsConfiguration, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setMinimumSize, setName, setPreferredSize, setRequestFocusController, setSize, setSize, setVisible, show, show, size, subtractAndApplyShape, subtractAndApplyShapeBelowMe, toString, transferFocus, transferFocus, transferFocusBackward, transferFocusBackward, transferFocusUpCycle, update, updateCursorImmediately, updateGraphicsData, updateZOrder, validate |
Methods from java.lang.Object: |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Method from javax.swing.JFormattedTextField Detail: |
public void commitEdit() throws ParseException {
AbstractFormatter format = getFormatter();
if (format != null) {
setValue(format.stringToValue(getText()), false, true);
}
}
Forces the current value to be taken from the
AbstractFormatter and set as the current value.
This has no effect if there is no current
AbstractFormatter installed. |
public Action[] getActions() {
return TextAction.augmentList(super.getActions(), defaultActions);
}
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. |
public int getFocusLostBehavior() {
return focusLostBehavior;
}
Returns the behavior when focus is lost. This will be one of
COMMIT_OR_REVERT ,
COMMIT ,
REVERT or
PERSIST
Note that some AbstractFormatter s may push changes as
they occur, so that the value of this will have no effect. |
public AbstractFormatter getFormatter() {
return format;
}
Returns the AbstractFormatter that is used to format and
parse the current value. |
public AbstractFormatterFactory getFormatterFactory() {
return factory;
}
Returns the current AbstractFormatterFactory . |
public String getUIClassID() {
return uiClassID;
}
Gets the class ID for a UI. |
public Object getValue() {
return value;
}
Returns the last valid value. Based on the editing policy of
the AbstractFormatter this may not return the current
value. The currently edited value can be obtained by invoking
commitEdit followed by getValue . |
protected void invalidEdit() {
UIManager.getLookAndFeel().provideErrorFeedback(JFormattedTextField.this);
}
Invoked when the user inputs an invalid value. This gives the
component a chance to provide feedback. The default
implementation beeps. |
public boolean isEditValid() {
return editValid;
}
Returns true if the current value being edited is valid. The value of
this is managed by the current AbstractFormatter , as such
there is no public setter for it. |
protected void processFocusEvent(FocusEvent e) {
super.processFocusEvent(e);
// ignore temporary focus event
if (e.isTemporary()) {
return;
}
if (isEdited() && e.getID() == FocusEvent.FOCUS_LOST) {
InputContext ic = getInputContext();
if (focusLostHandler == null) {
focusLostHandler = new FocusLostHandler();
}
// if there is a composed text, process it first
if ((ic != null) && composedTextExists) {
ic.endComposition();
EventQueue.invokeLater(focusLostHandler);
} else {
focusLostHandler.run();
}
}
else if (!isEdited()) {
// reformat
setValue(getValue(), true, true);
}
}
Processes any focus events, such as
FocusEvent.FOCUS_GAINED or
FocusEvent.FOCUS_LOST . |
protected void processInputMethodEvent(InputMethodEvent e) {
AttributedCharacterIterator text = e.getText();
int commitCount = e.getCommittedCharacterCount();
// Keep track of the composed text
if (text != null) {
int begin = text.getBeginIndex();
int end = text.getEndIndex();
composedTextExists = ((end - begin) > commitCount);
} else {
composedTextExists = false;
}
super.processInputMethodEvent(e);
}
Processes any input method events, such as
InputMethodEvent.INPUT_METHOD_TEXT_CHANGED or
InputMethodEvent.CARET_POSITION_CHANGED . |
public void setDocument(Document doc) {
if (documentListener != null && getDocument() != null) {
getDocument().removeDocumentListener(documentListener);
}
super.setDocument(doc);
if (documentListener == null) {
documentListener = new DocumentHandler();
}
doc.addDocumentListener(documentListener);
}
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. |
public void setFocusLostBehavior(int behavior) {
if (behavior != COMMIT && behavior != COMMIT_OR_REVERT &&
behavior != PERSIST && behavior != REVERT) {
throw new IllegalArgumentException("setFocusLostBehavior must be one of: JFormattedTextField.COMMIT, JFormattedTextField.COMMIT_OR_REVERT, JFormattedTextField.PERSIST or JFormattedTextField.REVERT");
}
focusLostBehavior = behavior;
}
Sets the behavior when focus is lost. This will be one of
JFormattedTextField.COMMIT_OR_REVERT ,
JFormattedTextField.REVERT ,
JFormattedTextField.COMMIT or
JFormattedTextField.PERSIST
Note that some AbstractFormatter s may push changes as
they occur, so that the value of this will have no effect.
This will throw an IllegalArgumentException if the object
passed in is not one of the afore mentioned values.
The default value of this property is
JFormattedTextField.COMMIT_OR_REVERT . |
protected void setFormatter(AbstractFormatter format) {
AbstractFormatter oldFormat = this.format;
if (oldFormat != null) {
oldFormat.uninstall();
}
setEditValid(true);
this.format = format;
if (format != null) {
format.install(this);
}
setEdited(false);
firePropertyChange("textFormatter", oldFormat, format);
}
Sets the current AbstractFormatter .
You should not normally invoke this, instead set the
AbstractFormatterFactory or set the value.
JFormattedTextField will
invoke this as the state of the JFormattedTextField
changes and requires the value to be reset.
JFormattedTextField passes in the
AbstractFormatter obtained from the
AbstractFormatterFactory .
This is a JavaBeans bound property. |
public void setFormatterFactory(AbstractFormatterFactory tf) {
AbstractFormatterFactory oldFactory = factory;
factory = tf;
firePropertyChange("formatterFactory", oldFactory, tf);
setValue(getValue(), true, false);
}
Sets the AbstractFormatterFactory .
AbstractFormatterFactory is
able to return an instance of AbstractFormatter that is
used to format a value for display, as well an enforcing an editing
policy.
If you have not explicitly set an AbstractFormatterFactory
by way of this method (or a constructor) an
AbstractFormatterFactory and consequently an
AbstractFormatter will be used based on the
Class of the value. NumberFormatter will
be used for Number s, DateFormatter will
be used for Dates , otherwise DefaultFormatter
will be used.
This is a JavaBeans bound property. |
public void setValue(Object value) {
if (value != null && getFormatterFactory() == null) {
setFormatterFactory(getDefaultFormatterFactory(value));
}
setValue(value, true, true);
}
Sets the value that will be formatted by an
AbstractFormatter obtained from the current
AbstractFormatterFactory . If no
AbstractFormatterFactory has been specified, this will
attempt to create one based on the type of value .
The default value of this property is null.
This is a JavaBeans bound property. |