public class JFormattedTextField extends JTextField
JFormattedTextField扩展了JTextField增加了格式化任意值的支持,以及一旦用户编辑了文本,就检索了一个特定的对象。
以下说明配置一个JFormattedTextField来编辑日期:
JFormattedTextField ftf = new JFormattedTextField();
ftf.setValue(new Date());
一旦创建了一个JFormattedTextField ,您可以通过添加PropertyChangeListener并监听PropertyChangeEvent s的属性名称value来监听编辑更改。
JFormattedTextField允许配置当焦点丢失时应采取什么动作。 可能的配置是:
Value
描述
JFormattedTextField.REVERT Revert the display to match that ofgetValue, 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.
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的JFormattedTextField.AbstractFormatter在通过install方法激活时通知,此时JFormattedTextField.AbstractFormatter可以安装任何需要的,通常为DocumentFilter 。 同样当JFormattedTextField不再需要AbstractFormatter时,它会调用uninstall 。
JFormattedTextField通常查询AbstractFormatterFactory为AbstractFormat在它获得或失去焦点。 虽然这可以根据焦点失去的政策而改变。 如果焦点JFormattedTextField.PERSIST政策是JFormattedTextField.PERSIST和JFormattedTextField已被编辑,那么AbstractFormatterFactory将不会被查询,直到该值被提交。 类似地,如果焦点丢失的策略是JFormattedTextField.COMMIT ,并且从stringToValue抛出异常,那么AbstractFormatterFactory将在焦点丢失或获得时不被查询。
JFormattedTextField.AbstractFormatter还负责确定何时提交到JFormattedTextField值。 一些JFormattedTextField.AbstractFormatter将使每个编辑都可以使用新的值,而其他的则不会提交该值。 您可以通过调用commitEdit从当前的JFormattedTextField.AbstractFormatter获取当前值。 commitEdit将在JFormattedTextField中按回车键时被调用。
如果AbstractFormatterFactory尚未明确设置,一个将根据设置类值类型的后setValue已被调用(假设值为非空)。 例如,在以下代码中,将创建适当的AbstractFormatterFactory和AbstractFormatter来处理数字格式:
JFormattedTextField tf = new JFormattedTextField();
tf.setValue(new Number(100));
警告:由于AbstractFormatter通常会安装一个DocumentFilter上Document和NavigationFilter上JFormattedTextField你不应该自己安装。 如果你这样做,你可能会看到奇怪的行为,因为AbstractFormatter的编辑政策将不会被执行。
警告: Swing不是线程安全的。 有关更多信息,请参阅Swing's Threading Policy 。
警告:此类的序列化对象与将来的Swing版本不兼容。 当前的序列化支持适用于运行相同版本的Swing的应用程序之间的短期存储或RMI。 从1.4开始,支持所有JavaBeans的长期存储已经添加到java.beans包中。 请参阅XMLEncoder 。
| Modifier and Type | Class and Description |
|---|---|
static class |
JFormattedTextField.AbstractFormatter
AbstractFormatter的
AbstractFormatter由
JFormattedTextField用于处理从对象到字符串以及从字符串返回到对象的转换。
|
static class |
JFormattedTextField.AbstractFormatterFactory
AbstractFormatterFactory的
AbstractFormatterFactory由
JFormattedTextField用于获取AbstractFormatter的
AbstractFormatter ,而这些
AbstractFormatter又用于格式化值。
|
JTextField.AccessibleJTextFieldJTextComponent.AccessibleJTextComponent, JTextComponent.DropLocation, JTextComponent.KeyBindingJComponent.AccessibleJComponentContainer.AccessibleAWTContainerComponent.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy| Modifier and Type | Field and Description |
|---|---|
static int |
COMMIT
常数确定当焦点丢失时,应调用
commitEdit 。
|
static int |
COMMIT_OR_REVERT
常数确定当焦点丢失时,应调用
commitEdit 。
|
static int |
PERSIST
常数确定当焦点丢失时,编辑的值应该保留。
|
static int |
REVERT
常数确定当焦点丢失时,编辑值应恢复为
JFormattedTextField上设置的当前值。
|
notifyActionDEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEYlistenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWaccessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTBOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WESTABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH| Constructor and Description |
|---|
JFormattedTextField()
创建一个
JFormattedTextField ,没有
AbstractFormatterFactory 。
|
JFormattedTextField(Format format)
创建一个
JFormattedTextField 。
|
JFormattedTextField(JFormattedTextField.AbstractFormatter formatter)
创建一个
JFormattedTextField与指定的
AbstractFormatter 。
|
JFormattedTextField(JFormattedTextField.AbstractFormatterFactory factory)
创建一个
JFormattedTextField与指定的
AbstractFormatterFactory 。
|
JFormattedTextField(JFormattedTextField.AbstractFormatterFactory factory, Object currentValue)
创建
JFormattedTextField与指定的
AbstractFormatterFactory和初始值。
|
JFormattedTextField(Object value)
创建一个具有指定值的JFormattedTextField。
|
| Modifier and Type | Method and Description |
|---|---|
void |
commitEdit()
强制从
AbstractFormatter的当前值并设置为当前值。
|
Action[] |
getActions()
获取编辑器命令列表。
|
int |
getFocusLostBehavior()
返回焦点丢失时的行为。
|
JFormattedTextField.AbstractFormatter |
getFormatter()
返回用于格式化和解析当前值的
AbstractFormatter 。
|
JFormattedTextField.AbstractFormatterFactory |
getFormatterFactory()
返回当前的
AbstractFormatterFactory 。
|
String |
getUIClassID()
获取UI的类ID。
|
Object |
getValue()
返回最后一个有效值。
|
protected void |
invalidEdit()
当用户输入无效值时调用。
|
boolean |
isEditValid()
如果正在编辑的当前值有效,则返回true。
|
protected void |
processFocusEvent(FocusEvent e)
处理任何焦点事件,例如
FocusEvent.FOCUS_GAINED或
FocusEvent.FOCUS_LOST 。
|
protected void |
processInputMethodEvent(InputMethodEvent e)
处理任何输入法事件,例如
InputMethodEvent.INPUT_METHOD_TEXT_CHANGED或
InputMethodEvent.CARET_POSITION_CHANGED 。
|
void |
setDocument(Document doc)
将编辑器与文本文档相关联。
|
void |
setFocusLostBehavior(int behavior)
设置焦点丢失时的行为。
|
protected void |
setFormatter(JFormattedTextField.AbstractFormatter format)
设置当前的
AbstractFormatter 。
|
void |
setFormatterFactory(JFormattedTextField.AbstractFormatterFactory tf)
设置
AbstractFormatterFactory 。
|
void |
setValue(Object value)
设置将通过从当前
AbstractFormatterFactory获取的
AbstractFormatter进行格式化的值。
|
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, setScrollOffsetaddCaretListener, 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, moveCaretPosition, paste, print, print, print, 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, setText, setUI, updateUI, viewToModel, writeaddAncestorListener, 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, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, updateadd, 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, validateTreeaction, 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, getPeer, 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, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCyclepublic static final int COMMIT
commitEdit 。
如果在提交新值时抛出ParseException ,则该值将保持不变。
public static final int COMMIT_OR_REVERT
commitEdit 。
如果提交新值,则抛出ParseException ,该值将被还原。
public static final int REVERT
JFormattedTextField上设置的当前值。
public static final int PERSIST
public JFormattedTextField()
JFormattedTextField ,没有AbstractFormatterFactory 。
使用setMask或setFormatterFactory配置JFormattedTextField来编辑特定类型的值。
public JFormattedTextField(Object value)
AbstractFormatterFactory的类型创建一个value 。
value -
value初始值
public JFormattedTextField(Format format)
JFormattedTextField 。
format被包裹在合适的AbstractFormatter ,然后包裹在一个AbstractFormatterFactory 。
format - 用于查找
format格式
public JFormattedTextField(JFormattedTextField.AbstractFormatter formatter)
JFormattedTextField与指定的AbstractFormatter 。
AbstractFormatter被放置在一个AbstractFormatterFactory 。
formatter - 用于格式化的抽象格式。
public JFormattedTextField(JFormattedTextField.AbstractFormatterFactory factory)
JFormattedTextField与指定的
AbstractFormatterFactory 。
factory - 用于格式化的AbstractFormatterFactory。
public JFormattedTextField(JFormattedTextField.AbstractFormatterFactory factory, Object currentValue)
JFormattedTextField与指定的
AbstractFormatterFactory和初始值。
factory -
AbstractFormatterFactory用于格式化。
currentValue - 要使用的初始值
public void setFocusLostBehavior(int behavior)
JFormattedTextField.COMMIT_OR_REVERT , JFormattedTextField.REVERT , JFormattedTextField.COMMIT或JFormattedTextField.PERSIST注意某些AbstractFormatter ,因为它们发生S可推动变化,从而使该值将没有任何效果。
这将引发IllegalArgumentException如果传入的对象不是上述提到的一个值。
此属性的默认值为JFormattedTextField.COMMIT_OR_REVERT 。
behavior - 识别焦点丢失时的行为
IllegalArgumentException - 如果行为不是已知值之一
public int getFocusLostBehavior()
COMMIT_OR_REVERT , COMMIT , REVERT或PERSIST注意某些AbstractFormatter ,因为它们发生S可推动变化,从而使该值将没有任何效果。
public void setFormatterFactory(JFormattedTextField.AbstractFormatterFactory tf)
AbstractFormatterFactory 。
AbstractFormatterFactory能够返回一个用于格式化显示值的AbstractFormatter实例,以及执行编辑策略。
如果你还没有明确设置一个AbstractFormatterFactory通过这种方法(或构造函数)的方式AbstractFormatterFactory ,因此一个AbstractFormatter将根据使用类价值。 NumberFormatter将用于Number s, DateFormatter将用于Dates , DefaultFormatter将使用DefaultFormatter 。
这是一个JavaBeans绑定属性。
tf -
AbstractFormatterFactory用于查找AbstractFormatter的
AbstractFormatter
public JFormattedTextField.AbstractFormatterFactory getFormatterFactory()
AbstractFormatterFactory 。
AbstractFormatterFactory用于确定
AbstractFormatter s
setFormatterFactory(javax.swing.JFormattedTextField.AbstractFormatterFactory)
protected void setFormatter(JFormattedTextField.AbstractFormatter format)
AbstractFormatter 。
你通常不应该调用这个,而是设置AbstractFormatterFactory或设置值。 JFormattedTextField将调用此为JFormattedTextField更改的状态,并要求该值重置。 JFormattedTextField通过在AbstractFormatter从所获得的AbstractFormatterFactory 。
这是一个JavaBeans绑定属性。
format - 用于格式化的抽象格式
setFormatterFactory(javax.swing.JFormattedTextField.AbstractFormatterFactory)
public JFormattedTextField.AbstractFormatter getFormatter()
AbstractFormatter 。
public void setValue(Object value)
AbstractFormatterFactory获取的AbstractFormatter进行格式化的值。
如果没有AbstractFormatterFactory AbstractFormatterFactory,则将尝试根据value的类型创建一个。
此属性的默认值为null。
这是一个JavaBeans绑定属性。
value - 要显示的当前值
public Object getValue()
AbstractFormatter的编辑策略,这可能不会返回当前值。
当前编辑的值可以通过调用commitEdit后跟getValue 。
public void commitEdit()
throws ParseException
AbstractFormatter获取当前值并将其设置为当前值。
如果没有安装当前的AbstractFormatter无效。
ParseException - 如果
AbstractFormatter无法格式化当前值
public boolean isEditValid()
AbstractFormatter管理,因此没有公共设置者。
protected void invalidEdit()
protected void processInputMethodEvent(InputMethodEvent e)
InputMethodEvent.INPUT_METHOD_TEXT_CHANGED或
InputMethodEvent.CARET_POSITION_CHANGED 。
processInputMethodEvent在
JTextComponent
e -
InputMethodEvent
InputMethodEvent
protected void processFocusEvent(FocusEvent e)
FocusEvent.FOCUS_GAINED或
FocusEvent.FOCUS_LOST 。
processFocusEvent在
Component
e -
FocusEvent
FocusEvent
public Action[] getActions()
getActions在
JTextField
public String getUIClassID()
getUIClassID在
JTextField
JComponent.getUIClassID()
public void setDocument(Document doc)
setDocument在
JTextField
doc - 显示/编辑的文档
JTextComponent.getDocument()
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved.