- 所有已实现的接口:
-
ImageObserver,MenuContainer,Serializable,Accessible,Scrollable,SwingConstants
JFormattedTextField扩展了JTextField,支持格式化任意值,并在用户编辑文本后检索特定对象。以下是配置JFormattedTextField以编辑日期的示例:
JFormattedTextField ftf = new JFormattedTextField(); ftf.setValue(new Date());
创建JFormattedTextField后,可以通过添加PropertyChangeListener并监听属性名称为value的PropertyChangeEvent来监听编辑更改。
JFormattedTextField允许配置在失去焦点时应采取的操作。可能的配置包括:
| 值 | 描述 |
|---|---|
| JFormattedTextField.REVERT | 将显示恢复为与getValue匹配的内容,可能会丢失当前编辑。 |
| JFormattedTextField.COMMIT | 提交当前值。如果正在编辑的值不被AbstractFormatter视为合法值,即抛出ParseException,则值不会更改,编辑的值将保留。 |
| JFormattedTextField.COMMIT_OR_REVERT | 类似于COMMIT,但如果值不合法,则行为类似于REVERT。 |
| JFormattedTextField.PERSIST | 不执行任何操作,不获取新的AbstractFormatter,也不更新值。 |
JFormattedTextField.COMMIT_OR_REVERT,有关更多信息,请参阅setFocusLostBehavior(int)。
JFormattedTextField允许焦点离开,即使当前编辑的值无效。要在JFormattedTextField处于无效编辑状态时锁定焦点,可以附加一个InputVerifier。以下代码片段展示了这样一个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);
}
}
或者,您可以调用commitEdit,这也会提交值。
JFormattedTextField本身不执行格式化,而是通过JFormattedTextField.AbstractFormatter的实例执行格式化,该实例是从JFormattedTextField.AbstractFormatterFactory的实例获取的。当JFormattedTextField.AbstractFormatter变为活动状态时,会通过install方法通知它们,此时JFormattedTextField.AbstractFormatter可以安装所需的任何内容,通常是DocumentFilter。类似地,当JFormattedTextField不再需要AbstractFormatter时,它将调用uninstall。
JFormattedTextField通常在获得或失去焦点时查询AbstractFormatterFactory以获取AbstractFormat。尽管这可能会根据焦点丢失策略而改变。如果焦点丢失策略为JFormattedTextField.PERSIST并且JFormattedTextField已被编辑,则在提交值之前不会查询AbstractFormatterFactory。类似地,如果焦点丢失策略为JFormattedTextField.COMMIT并且从stringToValue抛出异常,则在焦点丢失或获得时不会查询AbstractFormatterFactory。
JFormattedTextField.AbstractFormatter还负责确定何时将值提交给JFormattedTextField。一些JFormattedTextField.AbstractFormatter会在每次编辑时提供新值,而另一些则永远不会提交值。您可以通过调用commitEdit强制从当前JFormattedTextField.AbstractFormatter获取当前值。在JFormattedTextField中按下回车键时,将调用commitEdit。
如果未明确设置AbstractFormatterFactory,则在调用setValue后(假设值非空)将根据值类型的Class设置一个AbstractFormatterFactory。例如,在以下代码中,将创建一个适当的AbstractFormatterFactory和AbstractFormatter来处理数字的格式化:
JFormattedTextField tf = new JFormattedTextField(); tf.setValue(100);
警告:由于AbstractFormatter通常会在Document上安装DocumentFilter,并在JFormattedTextField上安装NavigationFilter,因此您不应该安装自己的DocumentFilter。如果这样做,可能会看到奇怪的行为,因为AbstractFormatter的编辑策略将不会得到执行。
警告:Swing不是线程安全的。有关更多信息,请参阅Swing的线程策略。
警告:此类的序列化对象将不兼容未来的Swing版本。当前的序列化支持适用于短期存储或在运行相同Swing版本的应用程序之间进行RMI。从1.4开始,已将所有JavaBeans的长期存储支持添加到java.beans包中。请参阅XMLEncoder。
- 自从:
- 1.4
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classAbstractFormatter的实例由JFormattedTextField用于处理从对象到字符串的转换,以及从字符串到对象的转换。static classAbstractFormatterFactory的实例由JFormattedTextField用于获取AbstractFormatter的实例,后者用于格式化值。Nested classes/interfaces declared in class javax.swing.JTextField
JTextField.AccessibleJTextFieldNested classes/interfaces declared in class javax.swing.text.JTextComponent
JTextComponent.AccessibleJTextComponent, JTextComponent.DropLocation, JTextComponent.KeyBindingNested classes/interfaces declared in class javax.swing.JComponent
JComponent.AccessibleJComponentNested classes/interfaces declared in class java.awt.Container
Container.AccessibleAWTContainerNested classes/interfaces declared in class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final int标识当焦点丢失时,应调用commitEdit的常量。static final int标识当焦点丢失时,应调用commitEdit的常量。static final int标识当焦点丢失时,应保留编辑的值的常量。static final int标识当焦点丢失时,应将编辑值恢复为JFormattedTextField上设置的当前值的常量。Fields declared in class javax.swing.JTextField
notifyActionFields declared in class javax.swing.text.JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEYFields declared in class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields declared in class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields declared in interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTHFields declared in 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
ConstructorsConstructorDescription创建一个没有AbstractFormatterFactory的JFormattedTextField。JFormattedTextField(Object value) 创建一个具有指定值的JFormattedTextField。JFormattedTextField(Format format) 创建一个JFormattedTextField。创建一个具有指定AbstractFormatter的JFormattedTextField。创建一个具有指定AbstractFormatterFactory的JFormattedTextField。JFormattedTextField(JFormattedTextField.AbstractFormatterFactory factory, Object currentValue) 创建一个具有指定AbstractFormatterFactory和初始值的JFormattedTextField。 -
Method Summary
Modifier and TypeMethodDescriptionvoid强制从AbstractFormatter获取当前值,并将其设置为当前值。Action[]获取编辑器的命令列表。int返回焦点丢失时的行为。返回用于格式化和解析当前值的AbstractFormatter。返回当前的AbstractFormatterFactory。获取UI的类ID。getValue()返回最后一个有效值。protected void当用户输入无效值时调用。boolean如果当前正在编辑的值有效,则返回true。protected void处理任何焦点事件,如FocusEvent.FOCUS_GAINED或FocusEvent.FOCUS_LOST。protected void处理任何输入方法事件,如InputMethodEvent.INPUT_METHOD_TEXT_CHANGED或InputMethodEvent.CARET_POSITION_CHANGED。voidsetDocument(Document doc) 将编辑器与文本文档关联。voidsetFocusLostBehavior(int behavior) 设置焦点丢失时的行为。protected void设置当前的AbstractFormatter。void设置AbstractFormatterFactory。void设置将由从当前AbstractFormatterFactory获取的AbstractFormatter格式化的值。Methods declared in class javax.swing.JTextField
actionPropertyChanged, addActionListener, configurePropertiesFromAction, createActionPropertyChangeListener, createDefaultModel, fireActionPerformed, getAccessibleContext, getAction, getActionListeners, getColumns, getColumnWidth, getHorizontalAlignment, getHorizontalVisibility, getPreferredSize, getScrollOffset, isValidateRoot, paramString, postActionEvent, removeActionListener, scrollRectToVisible, setAction, setActionCommand, setColumns, setFont, setHorizontalAlignment, setScrollOffsetMethods declared in class javax.swing.text.JTextComponent
addCaretListener, 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, read, removeCaretListener, removeKeymap, replaceSelection, restoreComposedText, saveComposedText, select, selectAll, setCaret, setCaretColor, setCaretPosition, setDisabledTextColor, setDragEnabled, setDropMode, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setText, setUI, updateUI, viewToModel, viewToModel2D, writeMethods declared in class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, 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, removeNotify, 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, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, updateMethods declared in 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, validateTreeMethods declared in class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, 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, 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, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
Field Details
-
COMMIT
public static final int COMMIT标识当焦点丢失时,应调用commitEdit的常量。如果在提交新值时抛出ParseException,则无效值将保留。- 参见:
-
COMMIT_OR_REVERT
public static final int COMMIT_OR_REVERT标识当焦点丢失时,应调用commitEdit的常量。如果在提交新值时抛出ParseException,则值将被恢复。- 参见:
-
REVERT
public static final int REVERT当焦点丢失时,编辑值应该恢复为JFormattedTextField上设置的当前值的常量标识。- 参见:
-
PERSIST
public static final int PERSIST当焦点丢失时,编辑值应该保留的常量标识。- 参见:
-
-
Constructor Details
-
JFormattedTextField
public JFormattedTextField()创建一个没有AbstractFormatterFactory的JFormattedTextField。使用setMask或setFormatterFactory来配置JFormattedTextField以编辑特定类型的值。 -
JFormattedTextField
创建一个具有指定值的JFormattedTextField。这将基于value的类型创建一个AbstractFormatterFactory。- 参数:
-
value- JFormattedTextField的初始值
-
JFormattedTextField
创建一个JFormattedTextField。format被包装在适当的AbstractFormatter中,然后被包装在AbstractFormatterFactory中。- 参数:
-
format- 用于查找AbstractFormatter的格式
-
JFormattedTextField
创建一个具有指定AbstractFormatter的JFormattedTextField。将AbstractFormatter放置在AbstractFormatterFactory中。- 参数:
-
formatter- 用于格式化的AbstractFormatter。
-
JFormattedTextField
创建一个具有指定AbstractFormatterFactory的JFormattedTextField。- 参数:
-
factory- 用于格式化的AbstractFormatterFactory。
-
JFormattedTextField
public JFormattedTextField(JFormattedTextField.AbstractFormatterFactory factory, Object currentValue) 创建一个具有指定AbstractFormatterFactory和初始值的JFormattedTextField。- 参数:
-
factory- 用于格式化的AbstractFormatterFactory。 -
currentValue- 要使用的初始值
-
-
Method Details
-
setFocusLostBehavior
@BeanProperty(bound=false, enumerationValues={"JFormattedTextField.COMMIT","JFormattedTextField.COMMIT_OR_REVERT","JFormattedTextField.REVERT","JFormattedTextField.PERSIST"}, description="Behavior when component loses focus") public void setFocusLostBehavior(int behavior) 设置焦点丢失时的行为。这将是JFormattedTextField.COMMIT_OR_REVERT、JFormattedTextField.REVERT、JFormattedTextField.COMMIT或JFormattedTextField.PERSIST中的一个。请注意,一些AbstractFormatter可能会在发生更改时推送更改,因此此值的更改将不会产生影响。如果传入的对象不是上述值之一,将抛出
IllegalArgumentException异常。此属性的默认值为
JFormattedTextField.COMMIT_OR_REVERT。- 参数:
-
behavior- 焦点丢失时的行为标识 - 抛出:
-
IllegalArgumentException- 如果行为不是已知值之一
-
getFocusLostBehavior
public int getFocusLostBehavior()返回焦点丢失时的行为。这将是COMMIT_OR_REVERT、COMMIT、REVERT或PERSIST中的一个。请注意,一些AbstractFormatter可能会在发生更改时推送更改,因此此值的更改将不会产生影响。- 返回:
- 返回焦点丢失时的行为
-
setFormatterFactory
@BeanProperty(visualUpdate=true, description="AbstractFormatterFactory, responsible for returning an AbstractFormatter that can format the current value.") public void setFormatterFactory(JFormattedTextField.AbstractFormatterFactory tf) 设置AbstractFormatterFactory。AbstractFormatterFactory能够返回用于显示值的AbstractFormatter实例,并强制执行编辑策略。如果您没有通过此方法(或构造函数)显式设置
AbstractFormatterFactory,则将基于值的Class使用NumberFormatter用于Number,DateFormatter用于Date,否则将使用DefaultFormatter。这是一个JavaBeans绑定属性。
- 参数:
-
tf- 用于查找AbstractFormatter实例的AbstractFormatterFactory
-
getFormatterFactory
返回当前的AbstractFormatterFactory。- 返回:
-
用于确定
AbstractFormatter的AbstractFormatterFactory - 参见:
-
setFormatter
设置当前的AbstractFormatter。通常不应调用此方法,而应设置
AbstractFormatterFactory或设置值。当JFormattedTextField的状态发生变化并需要重置值时,JFormattedTextField会调用此方法。JFormattedTextField会传入从AbstractFormatterFactory获取的AbstractFormatter。这是一个JavaBeans绑定属性。
- 参数:
-
format- 用于格式化的AbstractFormatter - 参见:
-
getFormatter
@BeanProperty(visualUpdate=true, description="TextFormatter, responsible for formatting the current value") public JFormattedTextField.AbstractFormatter getFormatter()返回用于格式化和解析当前值的AbstractFormatter。- 返回:
- 用于格式化的AbstractFormatter
-
setValue
@BeanProperty(visualUpdate=true, description="The value to be formatted.") public void setValue(Object value) 设置将由从当前AbstractFormatterFactory获取的AbstractFormatter格式化的值。如果未指定AbstractFormatterFactory,则将尝试根据value的类型创建一个。此属性的默认值为null。
这是一个JavaBeans绑定属性。
- 参数:
-
value- 要显示的当前值
-
getValue
返回最后一个有效值。根据AbstractFormatter的编辑策略,这可能不会返回当前值。当前编辑的值可以通过调用commitEdit后跟getValue来获取。- 返回:
- 最后一个有效值
-
commitEdit
强制从AbstractFormatter获取当前值,并将其设置为当前值。如果没有安装当前AbstractFormatter,则此操作无效。- 抛出:
-
ParseException- 如果AbstractFormatter无法格式化当前值
-
isEditValid
如果当前正在编辑的值有效,则返回true。此值由当前AbstractFormatter管理,因此没有公共setter方法。- 返回:
- 如果当前正在编辑的值有效,则返回true。
-
invalidEdit
protected void invalidEdit()当用户输入无效值时调用。这使组件有机会提供反馈。默认实现会发出哔哔声。 -
processInputMethodEvent
处理任何输入方法事件,例如InputMethodEvent.INPUT_METHOD_TEXT_CHANGED或InputMethodEvent.CARET_POSITION_CHANGED。- 覆盖:
-
processInputMethodEvent在类中Component - 参数:
-
e-InputMethodEvent - 参见:
-
processFocusEvent
处理任何焦点事件,例如FocusEvent.FOCUS_GAINED或FocusEvent.FOCUS_LOST。- 覆盖:
-
processFocusEvent在类中Component - 参数:
-
e-FocusEvent - 参见:
-
getActions
获取编辑器的命令列表。这是由插入的UI支持的命令列表,加上编辑器本身支持的命令集合。这些对于绑定到事件非常有用,例如在键映射中。- 覆盖:
-
getActions在类中JTextField - 返回:
- 命令列表
-
getUIClassID
获取UI的类ID。- 覆盖:
-
getUIClassID在类中JTextField - 返回:
- 字符串"FormattedTextFieldUI"
- 参见:
-
setDocument
@BeanProperty(expert=true, description="the text document model") public void setDocument(Document doc) 将编辑器与文本文档关联。当前注册的工厂用于为文档构建一个视图,该视图在重新验证后由编辑器显示。将向每个侦听器传播一个PropertyChange事件("document")。- 覆盖:
-
setDocument在类JTextField - 参数:
-
doc- 要显示/编辑的文档 - 参见:
-