- 所有已实现的接口:
-
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
Modifier and TypeClassDescriptionstatic class
AbstractFormatter
的实例由JFormattedTextField
用于处理从对象到字符串的转换,以及从字符串到对象的转换。static class
AbstractFormatterFactory
的实例由JFormattedTextField
用于获取AbstractFormatter
的实例,后者用于格式化值。Nested classes/interfaces declared in class javax.swing.JTextField
JTextField.AccessibleJTextField
Nested classes/interfaces declared in class javax.swing.text.JTextComponent
JTextComponent.AccessibleJTextComponent, JTextComponent.DropLocation, JTextComponent.KeyBinding
Nested classes/interfaces declared in class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes/interfaces declared in class java.awt.Container
Container.AccessibleAWTContainer
Nested classes/interfaces declared in class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
-
Field Summary
Modifier and TypeFieldDescriptionstatic final int
标识当焦点丢失时,应调用commitEdit
的常量。static final int
标识当焦点丢失时,应调用commitEdit
的常量。static final int
标识当焦点丢失时,应保留编辑的值的常量。static final int
标识当焦点丢失时,应将编辑值恢复为JFormattedTextField
上设置的当前值的常量。Fields declared in class javax.swing.JTextField
notifyAction
Fields declared in class javax.swing.text.JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
Fields declared in class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields declared in class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields declared in interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Fields 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
ConstructorDescription创建一个没有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
。void
setDocument
(Document doc) 将编辑器与文本文档关联。void
setFocusLostBehavior
(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, setScrollOffset
Methods 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, write
Methods 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, update
Methods 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, validateTree
Methods 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
- 要显示/编辑的文档 - 参见:
-