Using the JFC/Swing Packages |
Send Us Feedback! How is the coverage of text components on this page and the text field page? Are you finding the information you need? If not, what's missing? Please send us mail with these and other comments about text to tutorial@java.sun.com and include "swing text" in the subject.
JTextComponent
and its descendants implement Swing's editable text components. The following figure shows the text component hierarchy and groups the classes according to their capabilities:The plain text components (text field, password field, and text area) are the easiest and most commonly used components. In a few lines of code, you can easily create, configure, and use a plain text component in your program. The components that can display styled text (editor pane and text pane) typically require more effort to use. Most programmers using editor pane or text pane need to build a user interface that lets the user manipulate the text styles. Also, getting the content from a styled text component typically requires more code than a simple call to
getText
.Yet, as the diagram shows, both plain and styled text components inherit from
JTextComponent
. This abstract base class provides a highly-configurable and powerful foundation for text manipulation.JTextComponent
provides these customizable features for all of its descendants:The application shown below contains a customized text pane and a user interface for interacting with it: [PENDING: use bold or some other styled text in the html, and then retake the snapshot]
- Separate document (the model in the model/view split) to manage the component's content.
- Editing capabilities expressed through action commands.
- Customizable keymaps and key bindings.
- Support for infinite undo/redo.
- Pluggable caret and support for caret change listeners.
The lower text area is a log that reports all changes made to the text in the text pane. The status line at the bottom of the window reports either the location of the selection or the position of the caret, depending on whether text is selected.
Through this example application, you will learn both how to use a text component's capabilities and how to customize them. This section covers these topics:
Note: The main source file for this application isTextComponentDemo.java
. You also needLimitedStyledDocument.java
. You might need to set the proxy host on the command line to run this program.
Refer to How to Use Text Fields for information about text fields and password fields.
- Working With a Text Component's Document
- Listening for Changes on a Document
- Attaching GUI Controls to Text Editing Commands
- About Editor Kits
- Modifying the Default Keymap
- Implementing Undo and Redo
- Listening for Caret and Selection Changes
- Displaying Text from a URL
- The Text API
- Examples that Use Text Components
Working With a Text Component's Document
Like many other Swing components, a text component separates its content from its view. The content for a text component is managed by its document, which contains the text, supports editing of the text, and notifies listeners of changes to the text. A document is an instance of a class that implements theDocument
interface or itsStyledDocument
subinterface.The example application shown previously has a custom document,
LimitedStyledDocument
, that limits the number of characters that it can contain.LimitedStyledDocument
is a subclass ofDefaultStyledDocument
, the default document forJEditorPane
andJTextPane
.Here's the code from the example program that creates a
LimitedStyledDocument
and makes it the document for the text pane:To limit the characters allowed in the document,...where the member variables are declared... JTextPane textPane; static final int MAX_CHARACTERS = 200; ...in the constructor for the frame... //Create the document for the text area LimitedStyledDocument lpd = new LimitedStyledDocument( MAX_CHARACTERS); ... //Create the text pane and configure it textPane = new JTextPane(); ... textPane.setDocument(lpd);LimitedStyledDocument
overrides its superclass'sinsertString
method, which is called each time text is inserted into the document.In addition topublic void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if ((getLength() + str.length()) <= maxCharacters) super.insertString(offs, str, a); else Toolkit.getDefaultToolkit().beep(); }insertString
, custom documents commonly override theremove
method , which is called each time text is removed from the document.Another common use of a custom document, is to create a keystroke-validated text field (a field whose value is checked each time the field is edited). For two examples of validated text fields, refer to Creating a Validated Text Field.
For more information, see these API tables: Classes and Interfaces that Represent Documents and Useful Methods for Working with Documents.
Listening for Changes on a Document
A document notifies interested listeners of changes to the document. Use a document listener to perform an action when text is inserted or removed from a document, or when the style of some of the text changes.The
TextComponentDemo
program uses a document listener to update the change log whenever a change is made to the text pane. This line of code registers an instance ofMyDocumentListener
as a listener on theLimitedStyledDocument
used in the example:Here's the implementation ofLimitedStyledDocument lpd = new LimitedStyledDocument(MAX_CHARACTERS); lpd.addDocumentListener(new MyDocumentListener());MyDocumentListener
:The listener in our example displays the type of change that occurred and, if affected by the change, the length of the text. For general information about document listeners and document events, see How to Write a Document Listener.protected class MyDocumentListener implements DocumentListener { public void insertUpdate(DocumentEvent e) { update(e); } public void removeUpdate(DocumentEvent e) { update(e); } public void changedUpdate(DocumentEvent e) { AbstractDocument.DefaultDocumentEvent de = (AbstractDocument.DefaultDocumentEvent)e; //Display the type of edit that occurred changeLog.append(de.getPresentationName() + newline); } private void update(DocumentEvent e) { AbstractDocument.DefaultDocumentEvent de = (AbstractDocument.DefaultDocumentEvent)e; //Display the type of edit that occurred and //the resulting text length changeLog.append(de.getPresentationName() + ": text length = " + e.getDocument().getLength() + newline); } }Remember that the document for this text pane limits the number of characters allowed in the document. If you try to add text so that the maximum would be exceeded, the document blocks the change and the listener's
insertUpdate
method is not called. Document listeners are notified of changes only if the change has already occurred.Sometimes, you might be tempted to change the document's text from within a document listener. For example, if you have a text field that should contain only integers and the user enters some other type of data, you might want to change the text to
0
. However, you should never modify the contents of text component from within a document listener. In fact, if you attempt to modify the text in a text component from within a document listener, your program will likely deadlock! Instead, provide a custom document and override theinsert
andremove
methods. Creating a Validated Text Field shows you how.Attaching GUI Controls to Text Editing Commands
[PENDING: should probably say something somewhere about the actions being shared! They operate on the current selection. This is a bug in the example program because if you move the current selection to the bottom, uneditable, text area, you get lots of exceptions. How to fix?]A Swing text component supports standard editing commands such as cut, copy, and paste. Each editing command is represented and implemented by an action object. This makes it easy for you to attach a GUI control, such as a menu item or button, to a command and build a GUI around a text component.
Text fields, password fields, and text areas manage their own sets of actions. In contrast,
JEditorPane
andJTextPane
each use an instance ofEditorKit
to manage their sets of actions. For conceptual information about editor kits, see the next section, About Editor Kits. For now, you just need to know that an editor kit contains a collection of actions for an editor pane or a text pane.Use the
getActions
method on your text component or on its editor kit to get an array containing all of the actions supported by a particular text component. It's often convenient to load the array of actions into aHashtable
so your program can retrieve an action by name. Here's the code fromTextComponentDemo
that gets the actions from the text pane and loads them into aHashtable
:And here's a convenient method for retrieving an action by its name from the hashtable:private Hashtable createActionTable(JTextComponent textComponent) { Hashtable actions = new Hashtable(); Action[] actionsArray = textComponent.getActions(); for (int i = 0; i < actionsArray.length; i++) { Action a = actionsArray[i]; actions.put(a.getValue(Action.NAME), a); } return actions; }You can copy the first method unchanged into your program. For the second method, changeprivate Action getActionByName(String name) { return (Action)(actions.get(name)); }actions
to the name of your hashtable.Now, let's look at how the Cut menu item is created and attached to the action of removing text from the text component:
This code gets the action by name, changes the name to something simple, and then adds the action to the menu. That's all you need to do. The menu and the action take care of everything else. You'll note that the name of the action comes fromprotected JMenu createEditMenu() { JMenu menu = new JMenu("Edit"); ... Action action = getActionByName(DefaultEditorKit.cutAction); action.putValue(Action.NAME, "Cut"); menu.add(action); ...DefaultEditorKit
. This is the default editor kit used by editor pane for dealing with plain text. This kit provides actions for basic text editing.Setting up the Style menu is similar, except that the commands come from a different editor kit. Here's the code that creates the menu and puts the Bold menu item in it:
Theprotected JMenu createStyleMenu() { JMenu menu = new JMenu("Style"); Action action = new StyledEditorKit.BoldAction(); action.putValue(Action.NAME, "Bold"); menu.add(action); ...StyledEditorKit
is the default editor kit for a text pane. It understands a custom rich text format (called "Tim's Rich Text Format") and providesAction
subclasses to implement editing commands. So this code creates an instance of theBoldAction
class, changes the name, and puts it in the menu.In addition to attaching a GUI control to an action command, you can also bind a keystroke to an action. Modifying the Default Keymap shows you how.
See the Text Editing Commands API table for related API.
About Editor Kits
[PENDING: do a simple custom editor kit that colors comments in a java file?]This section provides some conceptual information about editor kits and conveys the power they bring to editor pane.
Besides managing a set of actions for a text component, an editor kit knows how to read and write documents of a particular format. The Swing text package provides editor kits for plain text, Tim's Rich Text Format, HTML, and RTF.
Each of these editor kits has been registered with the
DefaultEditorKit
- Reads and writes unstyled text. Provides a basic set of editing commands. This is the default editor kit used by editor pane when loading plain text or text of an unknown format.
StyledEditorKit
- Reads and writes Tim's Rich Text Format and provides a minimal set of actions for styled text. This class is a subclass of
DefaultEditorKit
This is the editor kit used byJTextPane
.HTMLEditorKit
- Reads, writes, and edits HTML. This is a subclass of
StyledEditorKit
.RTFEditorKit
- Reads, writes, and edits RTF. This is a subclass of
StyledEditorKit
.JEditorPane
class and associated with the text format that the kit understands. When a file is loaded into an editor pane, the pane checks the format of the file against its registered kits. If a registered kit is found that supports that file format, the pane uses the kit to read the file, display, and edit it. Thus, the editor pane effectively morphs itself into an editor for that text format.You can extend
JEditorPane
to support your own text format by creating an editor kit for it, and then usingJEditorPane
'sregisterEditorKitForContentType
to associate your kit with your text format.Modifying the Default Keymap
This section assumes that you understand actions and how to get them from the editor kit. If you don't, read Attaching GUI Controls to Text Editing Commands.Every text component has one or more keymaps-- each of which is an instance of the
Keymap
class. A keymap contains a collection of name-value pairs where the name is aKeyStroke
and the value is anAction
. Each pair binds the keystroke to the action such that when the user types the keystroke, the action occurs.By default, a text component has one keymap named
JTextComponent.DEFAULT_KEYMAP
. This keymap contains standard, basic key bindings. For example, the 'f' key on the keyboard is mapped to the action of entering an 'f' character into the text component, the arrow keys are mapped to caret movement, and so on. If you need to change the default key bindings, you will typically enhance or modify the default keymap in one of the following ways:Most programs don't replace the default keymap completely.
- Add a custom keymap to the text component with
JTextComponent
'saddKeymap
method.- Add key bindings to the default keymap with
Keymap
'saddActionForKeyStroke
method.- Remove key bindings from the default keymap with
Keymap
'sremoveKeyStrokeBinding
method.When resolving a keystroke to its action, the text component checks the keymaps in the order they are added to the text component. Thus, the binding for a specific keystroke in a keymap that you add to a text component overrides any binding for the same keystroke in the default keymap.
The text pane in the
TextComponentDemo
adds four key bindings to the default keymap.The following code adds the
CTRL-B
for moving the caret backward one characterCTRL-F
for moving the caret forward one characterCTRL-P
for moving the caret up one lineCTRL-N
for moving the caret down one lineCTRL-B
key binding to the default keymap. The code for adding the other three is similar.The code first gets the current keymap. Next, the code gets the backward action from the editor kit and gets a//Get the current, default map Keymap keymap = textPane.getKeymap(); //Ctrl-b to go backward one character Action action = getActionByName(DefaultEditorKit.backwardAction); KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK); keymap.addActionForKeyStroke(key, action);KeyStroke
object representing theCTRL-B
key sequence. Finally, the code adds the action and keystroke pair to the keymap, thereby binding the key to the action.For related API, see the Binding KeyStrokes to Actions API table.
Implementing Undo and Redo
Note: The implementation of undo and redo inTextComponentDemo
was copied directly from the NotePad demo that comes with Swing. Many programmers will also be able to copy this implementation of undo/redo without modification.
Implementing undo/redo has two parts:
- Remembering the undoable edits that occur.
- Implementing the undo and redo commands and providing a user interface for them.
Part 1: Remembering Undoable Edits
To support undo/redo, a text component must remember each edit that occurs on it, the order edits occur in relation to one another, and what it takes to undo it. The example program uses an undo manager, an instance of theUndoManager
class in Swing'sundo
package, to manage its list of undoable edits. The undo manager is created where the member variables are declared:Now, let's look at how the program finds out about undoable edits and adds them to the undo manager.protected UndoManager undo = new UndoManager();A document notifies interested listeners whenever an undoable edit occurs on its content. An important step in implementing undo and redo is register an undoable edit listener on the document of the text component. This code adds an instance of
MyUndoableEditListener
to the text pane's document:The undoable edit listener used in our example adds the edit to the undo manager's list:lpd.addUndoableEditListener(new MyUndoableEditListener());Note that this method updates two objects:protected class MyUndoableEditListener implements UndoableEditListener { public void undoableEditHappened(UndoableEditEvent e) { //Remember the edit and update the menus undo.addEdit(e.getEdit()); undoAction.update(); redoAction.update(); } }undoAction
andredoAction
. These are the action objects attached to the Undo and Redo menu items, respectively. The next step shows you how the menu items are created and the implementation of the two actions.For general information about undoable edit listeners and undoable edit events, see How to Write an Undoable Edit Listener.
Part 2: Implementing the Undo/Redo Commands
The first step in this part of implementing undo and redo is to create the actions to put in the Edit menu.The undo and redo actions are implemented by customJMenu menu = new JMenu("Edit"); //Undo and redo are actions of our own creation undoAction = new UndoAction(); menu.add(undoAction); redoAction = new RedoAction(); menu.add(redoAction); ...AbstractAction
subclasses:UndoAction
andRedoAction
respectively. These classes are inner classes of the example's primary class.When the user invokes the Undo command,
UndoAction
'sactionPerformed
method, shown here, gets called:This method calls the undo manager'spublic void actionPerformed(ActionEvent e) { try { undo.undo(); } catch (CannotUndoException ex) { System.out.println("Unable to undo: " + ex); ex.printStackTrace(); } update(); redoAction.update(); }undo
method and updates the menu items to reflect the new undo/redo state.Similarly, when the user invokes the Redo command, the
actionPerformed
method inRedoAction
gets called:This method is similar except that it calls the undo manager'spublic void actionPerformed(ActionEvent e) { try { undo.redo(); } catch (CannotRedoException ex) { System.out.println("Unable to redo: " + ex); ex.printStackTrace(); } update(); undoAction.update(); }redo
method.Much of the code in the
UndoAction
andRedoAction
classes is dedicated to enabling and disabling the actions as appropriate for the current state, and changing the names of the menu items to reflect the edit to be undone or redone.[PENDING: Can more be said here? Should talk more about what's in the undo package and about sharing undo managers between objects (or not).]
Listening for Caret and Selection Changes
TheTextComponentDemo
program uses a caret listener to display the current position of the caret or, if text is selected, the extent of the selection.The caret listener in this example is also a label. Here's the code that creates the caret listener label, adds it to the window, and makes it a caret listener of the text pane:
A caret listener must implement one method,//Create the status area JPanel statusPane = new JPanel(new GridLayout(1, 1)); CaretListenerLabel caretListenerLabel = new CaretListenerLabel( "Caret Status"); statusPane.add(caretListenerLabel); ... textPane.addCaretListener(caretListenerLabel);caretUpdate
, which is called each time the caret moves or the selection changes. Here's theCaretListenerLabel
implementation ofcaretUpdate
:As you can see, this listener updates its text label to reflect the current state of the caret or selection. The listener gets the information displayed from the caret event object. For general information about caret listeners and caret events, see How to Write a Caret Listener.public void caretUpdate(CaretEvent e) { //Get the location in the text int dot = e.getDot(); int mark = e.getMark(); if (dot == mark) { // no selection try { Rectangle caretCoords = textPane.modelToView(dot); //Convert it to view coordinates setText("caret: text position: " + dot + ", view location = [" + caretCoords.x + ", " + caretCoords.y + "]" + newline); } catch (BadLocationException ble) { setText("caret: text position: " + dot + newline); } } else if (dot < mark) { setText("selection from: " + dot + " to " + mark + newline); } else { setText("selection from: " + mark + " to " + dot + newline); } }As with document listeners, a caret listener is passive. It reacts to changes in the caret or in the selection but does not change the caret or the selection. Instead of modifying the caret or selection from a caret listener, you should use a custom caret. To create a custom caret, write a class that implements the
Caret
interface, then provide an instance of your class as an argument tosetCaret
on a text component.For related API, see the JTextComponent Methods for Manipulating the Current Selection and Manipulating Carets and Selection Highlighters API tables.
Displaying Text from a URL
Upon startup, the text pane inTextComponentsDemo
contains text. The program usessetPage
to load an HTML file into the text pane. Here's the code://Load the text area with text try { URL url = new URL("http://java.sun.com/docs/books/tutorial/ui/" + "swing/example-swing/TextComponentDemo.html"); textPane.setPage(url); } catch (Exception e ) { System.err.println("Can't open instructions"); }JTextPane
inherits thesetPage
method from its parentJEditorPane
class. The version ofsetPage
used in this example takes aURL
object as a parameter. Another version of the method requires aString
specification of a URL. The URL can specify an HTML, RTF, or plain text file.For information about related API, see API for Displaying Text from a URL.
The Text API
This section provides these text component API tables:
- Swing Text Component Classes
- JTextComponent Methods for Setting Attributes
- Converting Positions Between the Model and The View
- Classes and Interfaces that Represent Documents
- Useful Methods for Working with Documents
- JTextComponent Methods for Manipulating the Current Selection
- Manipulating Carets and Selection Highlighters
- Text Editing Commands
- Binding KeyStrokes to Actions
- Reading and Writing Text
- API for Displaying Text from a URL
Swing Text Component Classes Class Description JTextComponent
The abstract superclass of all Swing text components. JTextField
An optionally editable, single-line, plain text component. See How to Use Text Fields. JPasswordField
An optionally editable, single-line, plain text component that masks its content. See Providing a Password Field. JTextArea
An optionally editable, multi-line, plain text component. JEditorPane
An optionally editable, multi-line, styled text component. JTextPane
An optionally editable, multi-line, styled text component with support for named attributes.
JTextComponent Methods for Setting Attributes Method Description void setDisabledTextColor(Color)
Color getDisabledTextColor()Set or get the color used to display text when the text component is disabled. void setOpaque(boolean)
boolean getOpaque()Set or get whether the text component is completely opaque. void setMargin(Insets)
Insets getMargin()Set or get the margin between the text and the text component's border. void setEditable(boolean)
boolean isEditable()Set or get whether the user can edit the text in the text component.
Converting Positions Between the Model and the View Method Description int viewToModel(Point)
(inJTextComponent
)Convert the specified point in the view coordinate system to a position within the text. Rectangle modelToView(int)
(inJTextComponent
)Convert the specified position within the text to a rectangle in the view coordinate system.
Classes and Interfaces that Represent Documents Interface or Class Description Document
(an interface)Defines the API that must be implemented by all documents. AbstractDocument
(an interface)An abstract superclass implementation of the Document interface. This is the superclass for all documents provided by the Swing text package. PlainDocument
(a class)Implements the Document
interface. The default document for the plain text components (text field, password field, and text area). Additionally used by editor pane and text pane when loading plain text or text of an unknown format.StyledDocument
(an interface)A Document
subinterface. Defines the API that must be implemented by documents that support styled text.DefaultStyledDocument
(a class)Implements the StyledDocument
interface. The default document for the styled text components (editor pane and text pane).
Useful Methods for Working with Documents Method Description setDocument(Document)
Document getDocument()
(inJTextComponent
Set or get the document for a text component. Document createDefaultModel()
(inJTextField
Override this method in text field and its subclasses to create a custom document instead of the default PlainDocument
. Creating a Validated Field provides an example of overriding this method.void insertString(int, String, AttributeSet)
void remove(int, int)
(inDocument
)These methods are commonly overridden by custom documents. For an example of a custom document that overrides both of these methods, see Creating a Validated Field. void addDocumentListener(DocumentListener)
void removeDocumentListener(DocumentListener)
(inDocument
)Add or remove a document listener to a document. See Listening for Changes on a Document. void addUndoableEditListener(UndoableEditListener)
void removeUndoableEditListener(UndoableEditlistener)
(inDocument
)Add or remove an undoable edit listener to a document. Undoable edit listeners are used in Implementing Undo and Redo. int getLength()
Position getStartPosition()
Position getEndPosition()
String getText(int, int)
(inDocument
)Document
methods that return useful information about the document.Object getProperty(Object)
void putProperty(Object, Object)
(inDocument
)
Dictionary getDocumentProperties()
void setDocumentProperties(Dictionary)
(inAbstractDocument
)A Document
maintains a set of properties that you can manipulate with these methods. The example described in Using a Document Listener on a Text Field uses a property to name text components so that a shared document listener can identify the document from whence came an event.
JTextComponent Methods for Manipulating the Current Selection Method Description String getSelectedText()
Get the currently selected text. void selectAll()
void select(int, int)Select all text or select text within a start and end range. void setSelectionStart(int)
void setSelectionEnd(int)
int getSelectionStart()
int getSelectionEnd()Set or get extent of the current selection by index. void setSelectedTextColor(Color)
Color getSelectedTextColor()Set or get the color of selected text. void setSelectionColor(Color)
Color getSelectionColor()Set or get the background color of selected text.
Manipulating Carets and Selection Highlighters Interface, Class, or Method Description Caret
(an interface)Defines the API for objects that represent an insertion point within documents. DefaultCaret
(a class)The default caret used by all text components. void setCaret(Caret)
Caret getCaret()
(inJTextComponent
)Set or get the caret object used by a text component. void setCaretColor(Color)
Color getCaretColor()
(inJTextComponent
)Set or get the color of the caret. void setCaretPosition(Position)
void moveCaretPosition(int)
Position getCaretPosition()
(inJTextComponent
)Set or get the current position of the caret within the document. void addCaretListener(CaretListener)
void removeCaretListener(CaretListener)
(inJTextComponent
)Add or remove a caret listener to a text component. Highlighter
(an interface)Defines the API for objects used to highlight the current selection. DefaultHighlighter
(a class)The default highlighter used by all text components. void setHighlighter(Highlighter)
Highlighter getHighlighter()
(inJTextComponent
)Set or get the highlighter used by a text component.
Text Editing Commands Class or Method Description void cut()
void copy()
void paste()
void replaceSelection(String)
(inJTextComponent
)Cut, copy, and paste text using the system clipboard. EditorKit
(a class)Edit, read, and write text of a particular format. DefaultEditorKit
(a class)A concrete subclass of EditorKit
that provides the basic text editing capabilities.StyledEditorKit
(a class)A subclass of Default EditorKit
that provides additional editing capabilities for styled text.String xxxxAction
(inDefaultEditorKit
)The names of all the actions supported by the default editor kit. BeepAction
CopyAction
CutAction
DefaultKeyTypedAction
InsertBreakAction
InsertContentAction
InsertTabAction
PasteAction
(inDefaultEditorKit
)A collection inner classes that implement various text editing commands. AlignmentAction
BoldAction
FontFamilyAction
FontSizeAction
ForegroundAction
ItalicAction
StyledTextAction
UnderlineAction
(inStyledEditorKit
)A collection inner classes that implement various editing commands for styled text. Action[] getActions()
(inJTextComponent
)Get the actions supported by this component. This method gets the array of actions from the editor kit if one is used by the component.
Binding KeyStrokes to Actions Interface or Method Description Keymap
(an interface)An interface for managing a set of key bindings. A key binding is represented by a keystroke/action pair. Keymap addKeymap(nm, Keymap)
Keymap removeKeymap(nm)
Keymap getKeymap(nm)
(inJTextComponent
)Add or remove a keymap to the keymap hierarchy. Also get a keymap by name. Note that these are class methods. The keymap hierarchy is shared by all text components. void loadKeymap(Keymap, KeyBinding[], Action[])
(inJTextComponent
)Adds a set of key bindings to the specified keymap. This is a class method. void setKeymap(Keymap)
Keymap getKeymap()
(inJTextComponent
)Set or get the currently active keymap for a particular text component. void addActionForKeyStroke(KeyStroke, Action)
Action getAction(KeyStroke)
KeyStroke[] getKeyStrokesForAction(Action)
(inKeymap
)Set or get keystroke/action binding from a keymap. boolean isLocallyDefined(KeyStroke)
(inKeymap
)Get whether the specified keystroke is bound to an action in a keymap. void removeKeyStrokeBinding(KeyStroke)
void removeBindings()
(inKeymap
)Remove one or all key bindings from a keymap. void setDefaultAction(Action)
Action getDefaultAction()
(inKeymap
)Set or get the default action. This action is fired if a keystroke is not explicitly bound to an action. Action[] getBoundActions()
KeyStroke[] getBoundKeyStrokes()
(inKeymap
)Get an array containing all of the bound actions or keystrokes in a keymap.
Reading and Writing Text Method Description void JTextComponent.read(Reader, Object)
void JTextComponent.write(Writer)
(inJTextComponent
)Read or write text. void read(Reader, Document, int)
void read(InputStream, Document, int)
(inEditorKit
)Read text from a stream into a document. void write(Writer, Document, int, int)
void write(OutputStream, Document, int, int)
(inEditorKit
)Write text from a document to a stream.
API for Displaying Text from a URL Method or Constructor Description JEditorPane(URL)
JEditorPane(String)
(inJEditorPane
)Create an editor pane loaded with the text at the specified URL. setPage(URL)
setPage(String)
(inJEditorPane
)Load an editor pane (or text pane) with the text at the specified URL. URL getPage()
(inJEditorPane
)Get the URL for the editor pane's (or text pane's) current page. Examples that Use Text Components
This table shows the examples that use text components and where those examples are described.
Example Where Described Notes TextDemo.java
How to Use Text Fields Uses a basic text field and a basic text area. TextComponentDemo.java
This page Provides a customized text pane. Illustrates many text component features. TextFieldDemo.java
How to Use Text Fields Implements two different keystroke-validated text fields. PasswordDemo.java
How to Use Text Fields and
Using the SwingWorkerClassUses a password field. ToolBarDemo2.java
How to Use Tool Bars Puts a text field in a tool bar. CustomDialog.java
How to Use Dialogs Puts a validated text field in a dialog. Part of DialogDemo
(under the More Dialogs tab).TreeDemo.java
How to Use Trees Uses an editor pane to display help loaded from an HTML file.
Using the JFC/Swing Packages |