Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages

How to Use Text Components

The Swing API provides many levels of text capabilities from simple, plug-and-play components to support for building customized text components. This section describes the plug-and-play components. The Swing Connection provides two articles about more complex uses of text: The SwingText Package and Customize a Text Editor. You can also look at the two text examples included with the Swing release, NotePad and StylePad.


Send Us Feedback : We are trying to decide on the level of coverage we should provide for the Swing text API in the tutorial. Currently, we're only covering the use of the plug-and-play components. If you would like to see how-to information about other text topics, send us a note and tell us what topics you'd like to see covered here. Heck, send us an example we can use!

JTextComponent(in the API reference documentation) and its descendants implement all of the editable text components in Swing:

              JTextComponent
                    |
       +------------+------------+
       |            |            |   
   JTextField   JTextArea   JEditorPane
       |                         |
 JPasswordField              JTextPane

JTextField(in the API reference documentation), JPasswordField(in the API reference documentation), and JTextArea(in the API reference documentation) are easy-to-use, plug-and-play components. JEditorPane(in the API reference documentation) and JTextPane(in the API reference documentation) are intended to be subclassed to support custom text formats. However, JEditorPane provides one useful plug-and-play feature: you can easily load plain, HTML, or RTF text into a JEditorPane from a URL. The following is a snapshot of an application that displays each plug-and-play text component and a JEditorPane loaded with HTML.

Try this:
  1. Compile and run the application. The source file is EeyoreQuotes.java.
    See Getting Started with Swing if you need help.
  2. [PENDING: put more items here]

The following table summarizes the features that differentiate the plug-and-play text components used in the example program. The table can help you choose the right component for a specific task and shows you where to go for more information:

  JTextField(in the API reference documentation),
JPasswordField(in the API reference documentation)
JTextArea(in the API reference documentation) JEditorPane(in the API reference documentation)
Single Line Only X    
Plain Text Only X X  
Painless Read/Write X X  
Displays HTML/RTF     X
Loads from a URL     X
For Information and Examples How to Use Text Fields How to Use JTextArea How to Display Text from a URL

The table is self-explanatory except for the Painless Read/Write row. A class earns an 'X' in this category if the value returned from getText is sufficient to reconstruct the text contents of the object. JEditorPane does not get an 'X' here because getText returns plain text. All of the style information, such as the red text in the EeyoreQuotes example, is lost.

How to Use JTextArea

If you want an easy-to-use component for displaying and entering text, or if you need a new lightweight Swing component that is source compatible with java.awt.TextArea, JTextArea is for you.

[PENDING: write a JTextArea specific example that illustrates some more of the JTextArea APIs, particularly getting text and actions from it. until then...]

Here's the code from EeyoreQuotes.java that creates a JTextArea:

//create text area
String text = "It's snowing still. \nAnd freezing. \n" +
	      "However, we haven't had \nan earthquake lately.";
JTextArea textArea = new JTextArea(text);
textArea.setEditable(false);
textArea.setFont(demoFont);
textArea.setMargin(new Insets(5,5,5,5));
textArea.setPreferredSize(new Dimension(170,80));

The API for using text areas falls into three categories:

Setting or Getting the Text Area's Contents
Method or Constructor Purpose Example

JTextArea()
JTextArea(int, int)
JTextArea(String, int, int)
JTextArea(String)
JTextArea(Document)
JTextArea(Document, String, int, int)
Create a JTextArea instance, initializing it to contain the specified text. The int arguments set the number of rows and columns. This is used to compute the component's preferred height and width and may not be the actual number of columns displayed. [PENDING: talk about Document or remove that item in first column] EeyoreQuotes.java
void setText(String)
String getText()
Set or get the text displayed by the text area. [none yet]
void append(String) Append the specified text to the end of the text already in the text area. [none yet]
void insert(String, int) Insert the specified text at the position indicated. [none yet]
void replaceRange(String, int, int) Replace the text in the specified range with the specified text. [none yet]

Fine Tuning the Text Area's Appearance
Method or Constructor Purpose Example
setEditable(boolean)
boolean isEditable()
Set or get whether the user can edit the text in the text area. EeyoreQuotes.java
setForeground(Color);
Color getForeground()
Set or get the color of the text within the text area. [none yet]
setBackground(Color);
Color getBackground()
Set or get the background color of the text area. [none yet]
void setFont(Font);
Font getFont()
Set or get the font used by the text area. EeyoreQuotes.java
void setMargin(Insets);
Insets getMargin()
Set or get the number of pixels between the edge of the text area and the text on all four sides. EeyoreQuotes.java
void setLineWrap(boolean);
boolean getLineWrap()
Set or get whether the text in the text area wraps (or is cropped). [none yet]
void setTabSize(int);
int getTabSize()
Set or get the tab size in characters. [none yet]

Handling Events from a Text Area
Method or Constructor Purpose Example
[PENDING]    

How to Display Text from a URL

Although JEditorPane is intended to be subclassed and extended, it has one useful plug-and-play feature: displaying text from a URL. The URL can contain plain, HTML, or RTF text. Here's the code from EeyoreQuotes that does this:
//create html area
JEditorPane quotePane = null;
JScrollPane scrollPane = null;
try {
    URL url = new URL("http://javaweb/~mem/tutorial/ui/swing/" +
		      "example-swing/EeyoreQuote.html");
    quotePane = new JEditorPane(url);
    quotePane.setEditable(false);
    scrollPane = new JScrollPane(quotePane);
    scrollPane.setPreferredSize(new Dimension(300, 175));
    if (DEBUG)
	System.out.println(quotePane.getText());

} catch (java.io.IOException e) {
    scrollPane = new JScrollPane(new JTextArea("Can't find HTML file."));
    scrollPane.setFont(demoFont);
}
Alternatively, you can use the setPage(String) or setPage(URL) methods to set the URL from which to load text.


Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages