next up previous
Next: Document handling Up: The JTextComponent Previous: Saving and loading

Other JTextComponent significant methods

In this subsection we highlight the import methods associated with JTextComponent. Some ideas and concepts will be explained further in coming sections.

Every JTextComponent (or derivative) instance has an associated Document. Swing will assign a default which can be retrieved, but the document instance can be changed with the setDocument() method.

public Document setDocument(Document doc)
public Document getDocument()

We will discuss the Document class in the next section.

The following methods manage all text within the component. This group also includes a method to replace the selected text with the specified string.

public void setText(String t)
public String getText()
public String getSelectedText()
public void replaceSelection(String content)
public String getText(int offs, int len)

The caret (the blinking cursor) is used as part of the selection mechanism for a text component and can be controlled with the following methods:

public Caret getCaret()
public void setCaret(Caret c)
public void setCaretPosition(int position)
public int getCaretPosition()
public void moveCaretPosition(int pos)

Note the user is free to move, select and set the caret position inside a document in an application.

Selected text will be highlighted.

By default, Swing will assign a highlighted to each text component instance. The methods in this group manage the highlighted, allowing it to be changed to a custom version if desired.

public Highlighter getHighlighter()
public void setHighlighter(Highlighter h)

The colour for each text state (normal, disabled, and selected) can also be changed.

public Color getCaretColor()
public void setCaretColor(Color c)
public Color getSelectionColor()
public void setSelectionColor(Color c)
public Color getSelectedTextColor()
public void setSelectedTextColor(Color c)
public Color getDisabledTextColor()
public void setDisabledTextColor(Color c)

Text selection is a very important feature of the text component class hierarchy. These methods allow developers to programmatically select regions of text within the document.

public synchronized int getSelectionStart()
public synchronized void setSelectionStart(int selectionStart)
public synchronized int getSelectionEnd()
public synchronized void setSelectionEnd(int selectionEnd)
public void select(int selectionStart, int selectionEnd)
public synchronized void selectAll()


next up previous
Next: Document handling Up: The JTextComponent Previous: Saving and loading
Dave Marshall
4/14/1999