所有类


javax.swing
类 JTextField

java.lang.Object
  继承者 java.awt.Component
      继承者 java.awt.Container
          继承者 javax.swing.JComponent
              继承者 javax.swing.text.JTextComponent
                  继承者 javax.swing.JTextField
所有已实现的接口:
ImageObserver, MenuContainer, Serializable, Accessible, Scrollable, SwingConstants
直接已知子类:
DefaultTreeCellEditor.DefaultTextField, JFormattedTextField, JPasswordField

public class JTextField
   
   
   
   
extends JTextComponent
implements SwingConstants

JTextField 是一个轻量级组件,它允许编辑单行文本。有关使用文本字段的信息和示例,请参阅《The Java Tutorial》中的 How to Use Text Fields 一节。

JTextField 应与 java.awt.TextField 具有源代码兼容性,理应如此。此组件具有 java.awt.TextField 类中没有的功能。有关其他功能,请参考超类。

JTextField 具有建立字符串的方法,此字符串用作针对被激发的操作事件的命令字符串。java.awt.TextField 把字段文本用作针对 ActionEvent 的命令字符串。如果通过 setActionCommand 方法设置的命令字符串不为 null,则 JTextField 将使用该字符串来保持与 java.awt.TextField 的兼容性,否则将使用字段文本来保持兼容性。

setEchoChargetEchoChar 方法不是直接提供的,以避免可插入的外观的新实现意外公开密码字符。为了提供类似密码的服务,单独的类 JPasswordField 扩展了 JTextField,从而通过可插入外观独立地提供此服务。

通过添加 TextEventTextListener,可以监视 java.awt.TextField 的更改。在基于 JTextComponent 的组件中,通过 DocumentEvent 将更改从模型传播到 DocumentListenersDocumentEvent 给出了更改的位置和更改种类(如果需要)。代码片段可能看起来如下所示:


     DocumentListener myListener = ??;
     JTextField myArea = ??;
     myArea.getDocument().addDocumentListener(myListener);
 

JTextField 的水平对齐方式可以设置为左对齐、前端对齐、居中对齐、右对齐或尾部对齐。右对齐/尾部对齐在所需的字段文本尺寸小于为它分配的尺寸时使用。这是由 setHorizontalAlignmentgetHorizontalAlignment 方法确定的。默认情况下为前端对齐。

文本字段如何使用 VK_ENTER 事件取决于文本字段是否具有任何操作侦听器。如果具有操作侦听器,则 VK_ENTER 导致侦听器获取一个 ActionEvent,并使用 VK_ENTER 事件。这与 AWT 文本字段处理 VK_ENTER 事件的方式是兼容的。如果文本字段没有操作侦听器,则从 1.3 版本开始不使用 VK_ENTER 事件。而是处理祖先组件的绑定,这将启用 JFC/Swing 的默认按钮特性。

通过对模型进行扩展和改变所提供的默认模型,可以很容易创建自定义字段。例如,以下代码片段将创建一个仅保存大写字符的字段。即使文本从剪贴板中粘贴过来或者通过编程方式而更改,此代码片段也是有效的。



 public class UpperCaseField extends JTextField {
 
     public UpperCaseField(int cols) {
         super(cols);
     }
 
     protected Document createDefaultModel() {
         return new UpperCaseDocument();
     }
 
     static class UpperCaseDocument extends PlainDocument {
 
         public void insertString(int offs, String str, AttributeSet a) 
             throws BadLocationException {
 
             if (str == null) {
                 return;
             }
             char[] upper = str.toCharArray();
             for (int i = 0; i < upper.length; i++) {
                 upper[i] = Character.toUpperCase(upper[i]);
             }
             super.insertString(offs, new String(upper), a);
         }
     }
 }

 

警告:此类的已序列化对象与以后的 Swing 版本不兼容。当前序列化支持适用于短期存储,或适用于在运行相同 Swing 版本的应用程序之间进行 RMI(Remote Method Invocation,远程方法调用)。从 1.4 版本开始,已在 java.beans 包中添加了支持所有 JavaBeansTM 长期存储的功能。请参见 XMLEncoder

另请参见:
setActionCommand(java.lang.String), JPasswordField, addActionListener(java.awt.event.ActionListener)

嵌套类摘要
protected  classJTextField.AccessibleJTextField
          此类实现对 JTextField 类的可访问性支持。
 
从类 javax.swing.text.JTextComponent 继承的嵌套类/接口
JTextComponent.AccessibleJTextComponent, JTextComponent.KeyBinding
 
从类 javax.swing.JComponent 继承的嵌套类/接口
JComponent.AccessibleJComponent
 
从类 java.awt.Container 继承的嵌套类/接口
Container.AccessibleAWTContainer
 
从类 java.awt.Component 继承的嵌套类/接口
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
字段摘要
static StringnotifyAction
          发送通知(已接收字段内容)的动作名称。
 
从类 javax.swing.text.JTextComponent 继承的字段
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
 
从类 javax.swing.JComponent 继承的字段
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
从类 java.awt.Component 继承的字段
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
从接口 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
 
从接口 java.awt.image.ImageObserver 继承的字段
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
构造方法摘要
JTextField()
          构造一个新的 TextField
JTextField(Document doc, String text, int columns)
          构造一个新的 JTextField,它使用给定文本存储模型和给定的列数。
JTextField(int columns)
          构造一个具有指定列数的新的空 TextField
JTextField(String text)
          构造一个用指定文本初始化的新 TextField
JTextField(String text, int columns)
          构造一个用指定文本和列初始化的新 TextField
 
方法摘要
 voidaddActionListener(ActionListener l)
          添加指定的操作侦听器以从此文本字段接收操作事件。
protected  voidconfigurePropertiesFromAction(Action a)
          根据 Action 实例的值来设置 ActionEvent 源属性的工厂方法。
protected  PropertyChangeListenercreateActionPropertyChangeListener(Action a)
          创建 PropertyChangeListener 的工厂方法,在其 Action 实例上的属性发生变化时,PropertyChangeListener 用于更新 ActionEvent 源。
protected  DocumentcreateDefaultModel()
          如果没有显式给出构造时要使用的模型,则创建该模型的默认实现。
protected  voidfireActionPerformed()
          通知对此事件类型感兴趣的所有侦听器。
 AccessibleContextgetAccessibleContext()
          获得与此 JTextField 关联的 AccessibleContext
 ActiongetAction()
          返回此 ActionEvent 源当前设置的 Action,如果没有设置 Action 则返回 null
 ActionListener[]getActionListeners()
          返回通过 addActionListener() 添加到此 JTextField 中的所有 ActionListener 的数组。
 Action[]getActions()
          获取编辑器的命令列表。
 intgetColumns()
          返回此 TextField 中的列数。
protected  intgetColumnWidth()
          返回列宽度。
 intgetHorizontalAlignment()
          返回文本的水平对齐方式。
 BoundedRangeModelgetHorizontalVisibility()
          获取文本字段的可见性。
 DimensiongetPreferredSize()
          返回此 TextField 所需的首选大小 Dimensions
 intgetScrollOffset()
          获取滚动偏移量(以像素为单位)。
 StringgetUIClassID()
          获取 UI 的类 ID。
 booleanisValidateRoot()
          调用来自文本字段本身的 revalidate,将通过验证文本字段来处理,如果文本字段不包含在 JViewport 中,则在这种情况下将返回 false。
protected  StringparamString()
          返回此 JTextField 的字符串表示形式。
 voidpostActionEvent()
          通过将其指派给所有已注册的 ActionListener 对象来处理发生在此文本字段上的操作事件。
 voidremoveActionListener(ActionListener l)
          移除指定的操作侦听器,以便不再从此文本字段接收操作事件。
 voidscrollRectToVisible(Rectangle r)
          将字段向左或向右滚动。
 voidsetAction(Action a)
          设置 ActionEvent 源的 Action
 voidsetActionCommand(String command)
          设置用于操作事件的命令字符串。
 voidsetColumns(int columns)
          设置此 TextField 中的列数,然后验证布局。
 voidsetDocument(Document doc)
          将编辑器与一个文本文档关联。
 voidsetFont(Font f)
          设置当前字体。
 voidsetHorizontalAlignment(int alignment)
          设置文本的水平对齐方式。
 voidsetScrollOffset(int scrollOffset)
          获取滚动偏移量(以像素为单位)。
 
从类 javax.swing.text.JTextComponent 继承的方法
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paste, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setText, setUI, updateUI, viewToModel, write
 
从类 javax.swing.JComponent 继承的方法
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, 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, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, 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, update
 
从类 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, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
从类 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, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, 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, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
从类 java.lang.Object 继承的方法
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

字段详细信息

notifyAction

public static final String notifyAction
发送通知(已接收字段内容)的动作名称。通常它必须绑定到回车操作。

另请参见:
常量字段值
构造方法详细信息

JTextField

public JTextField()
构造一个新的 TextField。创建一个默认的模型,初始字符串为 null,列数设置为 0。


JTextField

public JTextField(String text)
构造一个用指定文本初始化的新 TextField。创建列数为 0 的默认模型。

参数:
text - 要显示的文本,或者为 null

JTextField

public JTextField(int columns)
构造一个具有指定列数的新的空 TextField。创建默认的模型,初始字符串设置为 null

参数:
columns - 用来计算首选宽度的列数;如果列设置为 0,则首选宽度将是组件实现的自然结果

JTextField

public JTextField(String text,
                  int columns)
构造一个用指定文本和列初始化的新 TextField。创建默认的模型。

参数:
text - 要显示的文本,或者为 null
columns - 用来计算首选宽度的列数;如果列被设置为 0,则首选宽度将是组件实现的自然结果

JTextField

public JTextField(Document doc,
                  String text,
                  int columns)
构造一个新的 JTextField,它使用给定文本存储模型和给定的列数。其他构造方法均调用此方法。如果文档为 null,则创建默认的模型。

参数:
doc - 要使用的文本存储;如果为 null,则通过调用 createDefaultModel 方法提供一个默认的存储
text - 要显示的初始文本,或者为 null
columns - 要用来计算首选宽度 >= 0 的列数;如果 columns 被设置为 0,则首选宽度将为组件实现的自然结果
抛出:
IllegalArgumentException - 如果 columns < 0
方法详细信息

getUIClassID

public String getUIClassID()
获取 UI 的类 ID。

覆盖:
JComponent 中的 getUIClassID
返回:
字符串 "TextFieldUI"
另请参见:
JComponent.getUIClassID(), UIDefaults.getUI(javax.swing.JComponent)

setDocument

public void setDocument(Document doc)
将编辑器与一个文本文档关联。当前注册的工厂用来生成文档的一个视图,此视图经过重新验证之后由编辑器来显示。将 PropertyChange 事件 ("document") 传播到每个侦听器。

覆盖:
JTextComponent 中的 setDocument
参数:
doc - 要显示/编辑的文档
另请参见:
JTextComponent.getDocument()

isValidateRoot

public boolean isValidateRoot()
调用来自文本字段本身的 revalidate,将通过验证文本字段来处理,如果文本字段不包含在 JViewport 中,则在这种情况下将返回 false。

覆盖:
JComponent 中的 isValidateRoot
返回:
如果此文本字段的父字段为 JViewPort,则返回 false;否则返回 true
另请参见:
JComponent.revalidate(), JComponent.isValidateRoot()