public class JTextField extends JTextComponent implements SwingConstants
JTextField是一个轻量级组件,允许编辑单行文本。
有关使用文本字段的信息和示例,请参阅Java Tutorial中的 How to Use Text Fields 。
JTextField旨在与java.awt.TextField进行源兼容,这样做是合理的。 该组件具有java.awt.TextField课程中找不到的java.awt.TextField 。 应咨询超类以获得更多功能。
JTextField有一个方法来建立用作被触发的动作事件的命令字符串的字符串。 java.awt.TextField使用字段的文本作为ActionEvent的命令字符串。 JTextField将使用setActionCommand方法的命令字符串设置,如果不是null ,否则将使用字段的文本作为与java.awt.TextField 。
不直接提供方法setEchoChar和getEchoChar以避免可插拔外观的新实现无意中暴露密码字符。 为了提供类似密码的服务,一个独立的类别JPasswordField扩展了JTextField ,为这项服务提供独立可插拔的外观。
java.awt.TextField可以通过为TextEvent添加一个TextListener来TextEvent变化。 在JTextComponent基组分,更改从模型经由广播DocumentEvent至DocumentListeners 。 DocumentEvent给出了更改的位置和更改的种类,如果需要的话。 代码片段可能如下所示:
DocumentListener myListener = ??; JTextField myArea = ??; myArea.getDocument().addDocumentListener(myListener);
JTextField的JTextField可以设为左对齐,前导对齐,居中,右对齐或尾随对齐。 如果字段文本的所需大小小于分配给它的大小,则右/尾对齐是有用的。 这是由setHorizontalAlignment和getHorizontalAlignment方法确定的。 默认是领先的。
文本字段消耗VK_ENTER事件的方式取决于文本字段是否有任何动作侦听器。 如果是这样,那么VK_ENTER会导致侦听器获取一个ActionEvent,并且VK_ENTER事件被消耗。 这与AWT文本字段如何处理VK_ENTER事件兼容。 如果文本字段没有动作侦听器,则从v 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's Threading Policy 。
警告:此类的序列化对象与将来的Swing版本不兼容。 当前的序列化支持适用于运行相同版本的Swing的应用程序之间的短期存储或RMI。 从1.4开始,对所有JavaBeans的长期存储的支持已经添加到java.beans包中。 请参阅XMLEncoder 。
| Modifier and Type | Class and Description |
|---|---|
protected class |
JTextField.AccessibleJTextField
这个类实现了
JTextField类的可访问性支持。
|
JTextComponent.AccessibleJTextComponent, JTextComponent.DropLocation, JTextComponent.KeyBindingJComponent.AccessibleJComponentContainer.AccessibleAWTContainerComponent.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy| Modifier and Type | Field and Description |
|---|---|
static String |
notifyAction
要发送通知的操作的名称,该字段的内容已被接受。
|
DEFAULT_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 |
|---|
JTextField()
构造新的
TextField 。
|
JTextField(Document doc, String text, int columns)
构造一个新的
JTextField ,它使用给定的文本存储模型和给定的列数。
|
JTextField(int columns)
构造一个新的空的
TextField与指定的列数。
|
JTextField(String text)
构造一个新的
TextField ,用指定的文本初始化。
|
JTextField(String text, int columns)
构造一个新的
TextField ,用指定的文本和列初始化。
|
| Modifier and Type | Method and Description |
|---|---|
protected void |
actionPropertyChanged(Action action, String propertyName)
响应相关操作中的属性更改更新文本框的状态。
|
void |
addActionListener(ActionListener l)
添加指定的动作侦听器以从此文本字段接收动作事件。
|
protected void |
configurePropertiesFromAction(Action a)
设置此文本字段上的属性以匹配指定的Action中的
Action 。
|
protected PropertyChangeListener |
createActionPropertyChangeListener(Action a)
创建并返回一个
PropertyChangeListener ,负责监听来自指定的变化
Action和更新相应的属性。
|
protected Document |
createDefaultModel()
如果没有明确给出,则创建要在构建中使用的模型的默认实现。
|
protected void |
fireActionPerformed()
通知所有在此事件类型上通知有兴趣的听众。
|
AccessibleContext |
getAccessibleContext()
获取
AccessibleContext与此相关
JTextField 。
|
Action |
getAction()
返回当前设置的
Action为
ActionEvent源,或
null如果没有设置
Action 。
|
ActionListener[] |
getActionListeners()
返回使用addActionListener()添加到此JTextField的所有
ActionListener的数组。
|
Action[] |
getActions()
获取编辑器命令列表。
|
int |
getColumns()
返回此
TextField中的列数。
|
protected int |
getColumnWidth()
返回列宽。
|
int |
getHorizontalAlignment()
返回文本的水平对齐。
|
BoundedRangeModel |
getHorizontalVisibility()
获取文本字段的可见性。
|
Dimension |
getPreferredSize()
返回首选大小
Dimensions为此需要
TextField 。
|
int |
getScrollOffset()
获取滚动偏移量,以像素为单位。
|
String |
getUIClassID()
获取UI的类ID。
|
boolean |
isValidateRoot()
呼叫
revalidate是来自文本字段本身内将通过验证文本字段,除非文本字段包含一个内处理
JViewport ,在这种情况下,这个返回false。
|
protected String |
paramString()
返回此
JTextField的字符串表示
JTextField 。
|
void |
postActionEvent()
通过将这些事件发送到任何已注册的
ActionListener对象来处理在此文本字段上发生的操作事件。
|
void |
removeActionListener(ActionListener l)
删除指定的动作监听器,使其不再从此文本字段接收动作事件。
|
void |
scrollRectToVisible(Rectangle r)
向左或向右滚动字段。
|
void |
setAction(Action a)
设置
Action为
ActionEvent源。
|
void |
setActionCommand(String command)
设置用于操作事件的命令字符串。
|
void |
setColumns(int columns)
设置此
TextField中的列数,然后使布局无效。
|
void |
setDocument(Document doc)
将编辑器与文本文档相关联。
|
void |
setFont(Font f)
设置当前字体。
|
void |
setHorizontalAlignment(int alignment)
设置文本的水平对齐方式。
|
void |
setScrollOffset(int scrollOffset)
设置滚动偏移量,以像素为单位。
|
addCaretListener, 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, processInputMethodEvent, 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, 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, transferFocusBackward, transferFocusUpCyclepublic static final String notifyAction
public JTextField()
TextField 。
创建默认模型,初始字符串为null ,列数设置为0。
public JTextField(String text)
TextField用指定文本初始化。
创建默认模型,列数为0。
text - 要显示的文本,或
null
public JTextField(int columns)
TextField与指定的列数。
创建默认模型,初始字符串设置为null 。
columns - 用于计算首选宽度的列数;
如果列设置为零,则首选宽度将是组件实现的任何自然结果
public JTextField(String text, int columns)
TextField ,用指定的文本和列进行初始化。
创建默认模型。
text - 要显示的文本,或
null
columns - 用于计算首选宽度的列数;
如果列设置为零,则首选宽度将是组件实现的任何自然结果
public JTextField(Document doc, String text, int columns)
JTextField ,它使用给定的文本存储模型和给定的列数。
这是其他构造函数通过其提供的构造函数。
如果文档是null ,则会创建默认模型。
doc - 要使用的文本存储;
如果是null ,将通过调用createDefaultModel方法提供默认值
text - 要显示的初始字符串,或
null
columns - 用于计算首选宽度> = 0的列数;
如果columns设置为零,则优选的宽度将是组件实现的任何自然结果
IllegalArgumentException - 如果
columns <0
public String getUIClassID()
getUIClassID在
JComponent
JComponent.getUIClassID() ,
UIDefaults.getUI(javax.swing.JComponent)
public void setDocument(Document doc)
setDocument在
JTextComponent
doc - 要显示/编辑的文档
JTextComponent.getDocument()
public boolean isValidateRoot()
revalidate是来自文本字段本身内将通过验证文本字段,除非文本字段包含一个内处理
JViewport ,在这种情况下,这个返回false。
isValidateRoot在
JComponent类
JViewPort返回false,否则返回true
JComponent.revalidate() ,
JComponent.isValidateRoot() ,
Container.isValidateRoot()
public int getHorizontalAlignment()
JTextField.LEFT JTextField.CENTER JTextField.RIGHT JTextField.LEADING JTextField.TRAILING public void setHorizontalAlignment(int alignment)
JTextField.LEFT JTextField.CENTER JTextField.RIGHT JTextField.LEADING JTextField.TRAILING invalidate和repaint ,并且PropertyChange事件(“horizontalAlignment”)。
alignment - 对齐
IllegalArgumentException - 如果
alignment不是有效的密钥
protected Document createDefaultModel()
PlainDocument的实例。
public int getColumns()
TextField中的列数。
public void setColumns(int columns)
TextField中的列数,然后使布局无效。
columns - 列数> = 0
IllegalArgumentException - 如果
columns小于0
protected int getColumnWidth()
public Dimension getPreferredSize()
Dimensions为此需要TextField 。
如果设置了非零数量的列,则将宽度设置为列乘以列宽。
getPreferredSize在
JComponent
JComponent.setPreferredSize(java.awt.Dimension) , ComponentUI
public void setFont(Font f)
revalidate在设置字体后调用。
setFont在
JComponent
f - 新字体
Component.getFont()
public void addActionListener(ActionListener l)
l - 要添加的动作侦听器
public void removeActionListener(ActionListener l)
l - 要删除的动作侦听器
public ActionListener[] getActionListeners()
ActionListener的数组。
ActionListener或一个空数组,如果没有添加任何监听器
protected void fireActionPerformed()
EventListenerList
public void setActionCommand(String command)
command - 命令字符串
public void setAction(Action a)
Action为ActionEvent源。
新Action替换任何以前设置Action但不影响ActionListeners与单独添加addActionListener 。
如果Action已经是ActionEvent的注册ActionListener为ActionEvent ,则不会重新注册。
设置Action会导致立即更改Swing Components Supporting Action中描述的所有属性 。 随后,文本框的属性会随着Action的属性发生更改而自动更新。
该方法使用其他三种方法来设置和帮助跟踪Action的属性值。 它使用configurePropertiesFromAction方法立即更改文本框的属性。 要跟踪Action的属性值中的更改,此方法注册PropertyChangeListener返回的createActionPropertyChangeListener 。 PropertyChangeListener调用actionPropertyChanged方法时, Action中的Action发生变化。
a -
Action为
JTextField ,或
null
Action , getAction() , configurePropertiesFromAction(javax.swing.Action) , createActionPropertyChangeListener(javax.swing.Action) , actionPropertyChanged(javax.swing.Action, java.lang.String)
public Action getAction()
Action为
ActionEvent源,或
null如果没有
Action设置。
Action为
ActionEvent源码,或
null
Action , setAction(javax.swing.Action)
protected void configurePropertiesFromAction(Action a)
Action 。
有关这些属性的详细信息,请参阅Swing Components Supporting Action 。
a -
Action从哪个获取属性,或
null
Action , setAction(javax.swing.Action)
protected void actionPropertyChanged(Action action, String propertyName)
PropertyChangeListener返回的createActionPropertyChangeListener调用的。
子类通常不需要调用它。
支持额外Action Action子类应该覆盖此和configurePropertiesFromAction 。
有关此方法设置的属性的列表,请参阅Swing Components Supporting Action的表。
action - 与
Action本字段相关联的Action
propertyName - 更改的属性的名称
Action , configurePropertiesFromAction(javax.swing.Action)
protected PropertyChangeListener createActionPropertyChangeListener(Action a)
PropertyChangeListener ,负责监听来自指定的变化Action和更新相应的属性。
警告:如果你这个子类不创建一个匿名的内部类。 如果你这样做的话,文本框的一生将被绑定到Action 。
a - 文本框的动作
Action , setAction(javax.swing.Action)
public Action[] getActions()
getActions在
JTextComponent
public void postActionEvent()
ActionListener对象来处理ActionListener本域上发生的操作事件。
这通常由注册在文本域中的控制器调用。
public BoundedRangeModel getHorizontalVisibility()
字段外观实现管理BoundedRangeModel上最小,最大和扩展属性的BoundedRangeModel 。
BoundedRangeModel
public int getScrollOffset()
public void setScrollOffset(int scrollOffset)
scrollOffset - offset> = 0
public void scrollRectToVisible(Rectangle r)
scrollRectToVisible在
JComponent
r - 要滚动的区域
JViewport
protected String paramString()
JTextField的字符串表示JTextField 。
该方法仅用于调试目的,并且返回的字符串的内容和格式可能因实现而异。
返回的字符串可能为空,但可能不是null 。
paramString在
JTextComponent
JTextField的字符串表示
JTextField
public AccessibleContext getAccessibleContext()
AccessibleContext与此相关JTextField 。
为JTextFields ,所述AccessibleContext需要一个的形式AccessibleJTextField 。
如有必要,将创建一个新的AccessibleJTextField实例。
getAccessibleContext在接口
Accessible
getAccessibleContext在
JTextComponent
AccessibleJTextField ,作为这个
AccessibleContext的
JTextField
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.