FileDocCategorySizeDatePackage
TextComponent.javaAPI DocJava SE 5 API41598Fri Aug 26 14:56:46 BST 2005java.awt

TextComponent

public class TextComponent extends Component implements Accessible
The TextComponent class is the superclass of any component that allows the editing of some text.

A text component embodies a string of text. The TextComponent class defines a set of methods that determine whether or not this text is editable. If the component is editable, it defines another set of methods that supports a text insertion caret.

In addition, the class defines methods that are used to maintain a current selection from the text. The text selection, a substring of the component's text, is the target of editing operations. It is also referred to as the selected text.

version
1.83, 05/05/04
author
Sami Shaio
author
Arthur van Hoff
since
JDK1.0

Fields Summary
String
text
The value of the text. A null value is the same as "".
boolean
editable
A boolean indicating whether or not this TextComponent is editable. It will be true if the text component is editable and false if not.
int
selectionStart
The selection refers to the selected text, and the selectionStart is the start position of the selected text.
int
selectionEnd
The selection refers to the selected text, and the selectionEnd is the end position of the selected text.
boolean
backgroundSetByClientCode
private transient boolean
canAccessClipboard
True if this TextComponent has access to the System clipboard.
protected transient TextListener
textListener
private static final long
serialVersionUID
private int
textComponentSerializedDataVersion
The textComponent SerializedDataVersion.
private boolean
checkForEnableIM
Constructors Summary
TextComponent(String text)
Constructs a new text component initialized with the specified text. Sets the value of the cursor to Cursor.TEXT_CURSOR.

param
text the text to be displayed; if text is null, the empty string "" will be displayed
exception
HeadlessException if GraphicsEnvironment.isHeadless returns true
see
java.awt.GraphicsEnvironment#isHeadless
see
java.awt.Cursor


                                                                                 		                                        
        
        GraphicsEnvironment.checkHeadless();
	this.text = (text != null) ? text : "";
	setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
	checkSystemClipboardAccess();
    
Methods Summary
public voidaddNotify()
Makes this Component displayable by connecting it to a native screen resource. This method is called internally by the toolkit and should not be called directly by programs.

see
java.awt.TextComponent#removeNotify

        super.addNotify();
        enableInputMethodsIfNecessary();
    
public synchronized voidaddTextListener(java.awt.event.TextListener l)
Adds the specified text event listener to receive text events from this text component. If l is null, no exception is thrown and no action is performed.

param
l the text event listener
see
#removeTextListener
see
#getTextListeners
see
java.awt.event.TextListener

	if (l == null) {
	    return;
	}
	textListener = AWTEventMulticaster.add(textListener, l);
        newEventsOnly = true;
    
booleanareInputMethodsEnabled()

        // moved from the constructor above to here and addNotify below, 
        // this call will initialize the toolkit if not already initialized.
        if (checkForEnableIM) {
            enableInputMethodsIfNecessary(); 
        }

        // TextComponent handles key events without touching the eventMask or
        // having a key listener, so just check whether the flag is set
        return (eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0;
    
private voidcheckSystemClipboardAccess()
Assigns a valid value to the canAccessClipboard instance variable.

        canAccessClipboard = true;
	SecurityManager sm = System.getSecurityManager();
	if (sm != null) {
	    try {
	        sm.checkSystemClipboardAccess();
	    }
	    catch (SecurityException e) {
	        canAccessClipboard = false;
	    }
	}
    
public voidenableInputMethods(boolean enable)

        checkForEnableIM = false;
        super.enableInputMethods(enable);
    
private voidenableInputMethodsIfNecessary()

	if (checkForEnableIM) {
            checkForEnableIM = false;
    	    try {
                Toolkit toolkit = Toolkit.getDefaultToolkit();
                boolean shouldEnable = false;            
                if (toolkit instanceof InputMethodSupport) {
                    shouldEnable = ((InputMethodSupport)toolkit)
                      .enableInputMethodsForTextComponent();
                }
                enableInputMethods(shouldEnable);
            } catch (Exception e) {
                // if something bad happens, just don't enable input methods
	    }
        }
    
booleaneventEnabled(java.awt.AWTEvent e)

        if (e.id == TextEvent.TEXT_VALUE_CHANGED) {
            if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0 ||
                textListener != null) {
                return true;
            } 
            return false;
        }
        return super.eventEnabled(e);
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Gets the AccessibleContext associated with this TextComponent. For text components, the AccessibleContext takes the form of an AccessibleAWTTextComponent. A new AccessibleAWTTextComponent instance is created if necessary.

return
an AccessibleAWTTextComponent that serves as the AccessibleContext of this TextComponent

        if (accessibleContext == null) {
            accessibleContext = new AccessibleAWTTextComponent();
        }
        return accessibleContext;
    
public java.awt.ColorgetBackground()
Gets the background color of this text component. By default, non-editable text components have a background color of SystemColor.control. This default can be overridden by calling setBackground.

return
This text component's background color. If this text component does not have a background color, the background color of its parent is returned.
see
#setBackground(Color)
since
JDK1.0

        if (!editable && !backgroundSetByClientCode) {
            return SystemColor.control;
        }

        return super.getBackground();
    
public synchronized intgetCaretPosition()
Returns the position of the text insertion caret. The caret position is constrained to be between 0 and the last character of the text, inclusive. If the text or caret have not been set, the default caret position is 0.

return
the position of the text insertion caret
see
#setCaretPosition(int)
since
JDK1.1

        TextComponentPeer peer = (TextComponentPeer)this.peer;
	int position = 0;

	if (peer != null) {
	    position = peer.getCaretPosition();
	} else {
	    position = selectionStart;
	}
	return position;
    
java.awt.RectanglegetCharacterBounds(int i)

        return null;
/* To be fully implemented in a future release
	if (peer == null) {
	    return null;
	}
	TextComponentPeer peer = (TextComponentPeer)this.peer;
	return peer.getCharacterBounds(i);
*/
    
intgetIndexAtPoint(java.awt.Point p)

	return -1;
/* To be fully implemented in a future release
	if (peer == null) {
	    return -1;
	}
	TextComponentPeer peer = (TextComponentPeer)this.peer;
	return peer.getIndexAtPoint(p.x, p.y);
*/
    
public java.awt.im.InputMethodRequestsgetInputMethodRequests()

        TextComponentPeer peer = (TextComponentPeer)this.peer;
        if (peer != null) return peer.getInputMethodRequests();
        else return null;
    
public T[]getListeners(java.lang.Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this TextComponent. FooListeners are registered using the addFooListener method.

You can specify the listenerType argument with a class literal, such as FooListener.class. For example, you can query a TextComponent t for its text listeners with the following code:

TextListener[] tls = (TextListener[])(t.getListeners(TextListener.class));
If no such listeners exist, this method returns an empty array.

param
listenerType the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
return
an array of all objects registered as FooListeners on this text component, or an empty array if no such listeners have been added
exception
ClassCastException if listenerType doesn't specify a class or interface that implements java.util.EventListener
see
#getTextListeners
since
1.3

	EventListener l = null; 
	if  (listenerType == TextListener.class) { 
	    l = textListener;
	} else {
	    return super.getListeners(listenerType);
	}
	return AWTEventMulticaster.getListeners(l, listenerType);
    
public synchronized java.lang.StringgetSelectedText()
Returns the selected text from the text that is presented by this text component.

return
the selected text of this text component
see
java.awt.TextComponent#select

	return getText().substring(getSelectionStart(), getSelectionEnd());
    
public synchronized intgetSelectionEnd()
Gets the end position of the selected text in this text component.

return
the end position of the selected text
see
java.awt.TextComponent#setSelectionEnd
see
java.awt.TextComponent#getSelectionStart

	TextComponentPeer peer = (TextComponentPeer)this.peer;
	if (peer != null) {
	    selectionEnd = peer.getSelectionEnd();
	}
	return selectionEnd;
    
public synchronized intgetSelectionStart()
Gets the start position of the selected text in this text component.

return
the start position of the selected text
see
java.awt.TextComponent#setSelectionStart
see
java.awt.TextComponent#getSelectionEnd

	TextComponentPeer peer = (TextComponentPeer)this.peer;
	if (peer != null) {
	    selectionStart = peer.getSelectionStart();
	}
	return selectionStart;
    
public synchronized java.lang.StringgetText()
Returns the text that is presented by this text component. By default, this is an empty string.

return
the value of this TextComponent
see
java.awt.TextComponent#setText

	TextComponentPeer peer = (TextComponentPeer)this.peer;
	if (peer != null) {
	    text = peer.getText();
	}
	return text;
    
public synchronized java.awt.event.TextListener[]getTextListeners()
Returns an array of all the text listeners registered on this text component.

return
all of this text component's TextListeners or an empty array if no text listeners are currently registered
see
#addTextListener
see
#removeTextListener
since
1.4

        return (TextListener[])(getListeners(TextListener.class));
    
public booleanisEditable()
Indicates whether or not this text component is editable.

return
true if this text component is editable; false otherwise.
see
java.awt.TextComponent#setEditable
since
JDK1.0

	return editable;
    
protected java.lang.StringparamString()
Returns a string representing the state of this TextComponent. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

return
the parameter string of this text component

	String str = super.paramString() + ",text=" + getText();
	if (editable) {
	    str += ",editable";
	}
	return str + ",selection=" + getSelectionStart() + "-" + getSelectionEnd();
    
protected voidprocessEvent(java.awt.AWTEvent e)
Processes events on this text component. If the event is a TextEvent, it invokes the processTextEvent method else it invokes its superclass's processEvent.

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

param
e the event

        if (e instanceof TextEvent) {
            processTextEvent((TextEvent)e);
            return;
        }
	super.processEvent(e);
    
protected voidprocessTextEvent(java.awt.event.TextEvent e)
Processes text events occurring on this text component by dispatching them to any registered TextListener objects.

NOTE: This method will not be called unless text events are enabled for this component. This happens when one of the following occurs:

  • A TextListener object is registered via addTextListener
  • Text events are enabled via enableEvents

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

param
e the text event
see
Component#enableEvents

        TextListener listener = textListener;
        if (listener != null) {
            int id = e.getID();
	    switch (id) {
	    case TextEvent.TEXT_VALUE_CHANGED:
		listener.textValueChanged(e);
		break;
	    }
        }
    
private voidreadObject(java.io.ObjectInputStream s)
Read the ObjectInputStream, and if it isn't null, add a listener to receive text events fired by the TextComponent. Unrecognized keys or values will be ignored.

exception
HeadlessException if GraphicsEnvironment.isHeadless() returns true
see
#removeTextListener()
see
#addTextListener()
see
java.awt.GraphicsEnvironment#isHeadless

        GraphicsEnvironment.checkHeadless();
        s.defaultReadObject();

        // Make sure the state we just read in for text, 
        // selectionStart and selectionEnd has legal values
	this.text = (text != null) ? text : "";
        select(selectionStart, selectionEnd);

        Object keyOrNull;
        while(null != (keyOrNull = s.readObject())) {
	    String key = ((String)keyOrNull).intern();

	    if (textListenerK == key) {
	        addTextListener((TextListener)(s.readObject()));
            } else { 
                // skip value for unrecognized key
	        s.readObject();
            }
        }
	enableInputMethodsIfNecessary();
	checkSystemClipboardAccess();
    
public voidremoveNotify()
Removes the TextComponent's peer. The peer allows us to modify the appearance of the TextComponent without changing its functionality.

        synchronized (getTreeLock()) {
	    TextComponentPeer peer = (TextComponentPeer)this.peer;
	    if (peer != null) {
	        text = peer.getText();
		selectionStart = peer.getSelectionStart();
		selectionEnd = peer.getSelectionEnd();
	    }
	    super.removeNotify();
	}
    
public synchronized voidremoveTextListener(java.awt.event.TextListener l)
Removes the specified text event listener so that it no longer receives text events from this text component If l is null, no exception is thrown and no action is performed.

param
l the text listener
see
#addTextListener
see
#getTextListeners
see
java.awt.event.TextListener
since
JDK1.1

	if (l == null) {
	    return;
	}
	textListener = AWTEventMulticaster.remove(textListener, l);
    
public synchronized voidselect(int selectionStart, int selectionEnd)
Selects the text between the specified start and end positions.

This method sets the start and end positions of the selected text, enforcing the restriction that the start position must be greater than or equal to zero. The end position must be greater than or equal to the start position, and less than or equal to the length of the text component's text. The character positions are indexed starting with zero. The length of the selection is endPosition - startPosition, so the character at endPosition is not selected. If the start and end positions of the selected text are equal, all text is deselected.

If the caller supplies values that are inconsistent or out of bounds, the method enforces these constraints silently, and without failure. Specifically, if the start position or end position is greater than the length of the text, it is reset to equal the text length. If the start position is less than zero, it is reset to zero, and if the end position is less than the start position, it is reset to the start position.

param
selectionStart the zero-based index of the first character (char value) to be selected
param
selectionEnd the zero-based end position of the text to be selected; the character (char value) at selectionEnd is not selected
see
java.awt.TextComponent#setSelectionStart
see
java.awt.TextComponent#setSelectionEnd
see
java.awt.TextComponent#selectAll

	String text = getText();
	if (selectionStart < 0) {
	    selectionStart = 0;
	}
	if (selectionStart > text.length()) {
	    selectionStart = text.length();
	}
	if (selectionEnd > text.length()) {
	    selectionEnd = text.length();
	}
	if (selectionEnd < selectionStart) {
	    selectionEnd = selectionStart;
	}

	this.selectionStart = selectionStart;
	this.selectionEnd = selectionEnd;

	TextComponentPeer peer = (TextComponentPeer)this.peer;
	if (peer != null) {
	    peer.select(selectionStart, selectionEnd);
	}
    
public synchronized voidselectAll()
Selects all the text in this text component.

see
java.awt.TextComponent#select

	String text = getText();
	this.selectionStart = 0;
	this.selectionEnd = getText().length();

	TextComponentPeer peer = (TextComponentPeer)this.peer;
	if (peer != null) {
	    peer.select(selectionStart, selectionEnd);
	}
    
public voidsetBackground(java.awt.Color c)
Sets the background color of this text component.

param
c The color to become this text component's color. If this parameter is null then this text component will inherit the background color of its parent.
see
#getBackground()
since
JDK1.0

        backgroundSetByClientCode = true;
        super.setBackground(c);
    
public synchronized voidsetCaretPosition(int position)
Sets the position of the text insertion caret. The caret position is constrained to be between 0 and the last character of the text, inclusive. If the passed-in value is greater than this range, the value is set to the last character (or 0 if the TextComponent contains no text) and no error is returned. If the passed-in value is less than 0, an IllegalArgumentException is thrown.

param
position the position of the text insertion caret
exception
IllegalArgumentException if position is less than zero
since
JDK1.1

	if (position < 0) {
	    throw new IllegalArgumentException("position less than zero.");
	}

	int maxposition = getText().length();
	if (position > maxposition) {
	    position = maxposition;
	}

	TextComponentPeer peer = (TextComponentPeer)this.peer;
	if (peer != null) {
	    peer.setCaretPosition(position);
	} else {
	    select(position, position);
	}
    
public synchronized voidsetEditable(boolean b)
Sets the flag that determines whether or not this text component is editable.

If the flag is set to true, this text component becomes user editable. If the flag is set to false, the user cannot change the text of this text component. By default, non-editable text components have a background color of SystemColor.control. This default can be overridden by calling setBackground.

param
b a flag indicating whether this text component is user editable.
see
java.awt.TextComponent#isEditable
since
JDK1.0

        if (editable == b) {
            return;
        }

	editable = b;
	TextComponentPeer peer = (TextComponentPeer)this.peer;
	if (peer != null) {
	    peer.setEditable(b);
	}
    
public synchronized voidsetSelectionEnd(int selectionEnd)
Sets the selection end for this text component to the specified position. The new end point is constrained to be at or after the current selection start. It also cannot be set beyond the end of the component's text. If the caller supplies a value for selectionEnd that is out of bounds, the method enforces these constraints silently, and without failure.

param
selectionEnd the end position of the selected text
see
java.awt.TextComponent#getSelectionEnd
see
java.awt.TextComponent#setSelectionStart
since
JDK1.1

	/* Route through select method to enforce consistent policy
    	 * between selectionStart and selectionEnd.
    	 */
	select(getSelectionStart(), selectionEnd);
    
public synchronized voidsetSelectionStart(int selectionStart)
Sets the selection start for this text component to the specified position. The new start point is constrained to be at or before the current selection end. It also cannot be set to less than zero, the beginning of the component's text. If the caller supplies a value for selectionStart that is out of bounds, the method enforces these constraints silently, and without failure.

param
selectionStart the start position of the selected text
see
java.awt.TextComponent#getSelectionStart
see
java.awt.TextComponent#setSelectionEnd
since
JDK1.1

	/* Route through select method to enforce consistent policy
    	 * between selectionStart and selectionEnd.
    	 */
	select(selectionStart, getSelectionEnd());
    
public synchronized voidsetText(java.lang.String t)
Sets the text that is presented by this text component to be the specified text.

param
t the new text; if this parameter is null then the text is set to the empty string ""
see
java.awt.TextComponent#getText

	text = (t != null) ? t : "";
	TextComponentPeer peer = (TextComponentPeer)this.peer;
	if (peer != null) {
	    peer.setText(text);
	}
    
private voidwriteObject(java.io.ObjectOutputStream s)
Writes default serializable fields to stream. Writes a list of serializable TextListener(s) as optional data. The non-serializable TextListener(s) are detected and no attempt is made to serialize them.

serialData
Null terminated sequence of zero or more pairs. A pair consists of a String and Object. The String indicates the type of object and is one of the following : textListenerK indicating and TextListener object.
see
AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
see
java.awt.Component#textListenerK


                                                                                                                                
       
        
    
        // Serialization support.  Since the value of the fields
        // selectionStart, selectionEnd, and text aren't necessarily
        // up to date, we sync them up with the peer before serializing.
        TextComponentPeer peer = (TextComponentPeer)this.peer;
        if (peer != null) {
            text = peer.getText();
            selectionStart = peer.getSelectionStart();
            selectionEnd = peer.getSelectionEnd();
        }

        s.defaultWriteObject();

        AWTEventMulticaster.save(s, textListenerK, textListener);
        s.writeObject(null);