Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Swing Components

An Example of Using Each Text Component

Here's a picture of an application that shows one of each of Swing's text components.

Try this:
  1. Compile and run the application. The source code is in TextSamplerDemo.java. You will also need TextSamplerDemoHelp.html, Pig.gif, dukeWaveRed.gif, and sound.gif.
    See Getting Started with Swing if you need help.
  2. Type text in the text field and press Return. Do the same with the password field.
  3. Select and edit text in the text area and the text pane. Use special keyboard keys to cut, copy, and paste text.
  4. Try to edit the text in the editor pane, which has been made uneditable with a call to setEditable.
  5. Scroll the text pane to find an example of an embedded component.

The TextSamplerDemo program is fairly basic in how it uses the text components: It simply creates each one, configures it, and adds it to the application's frame.

This section shows you the code used in TextSamplerDemo to create each text component. With the information in this short section alone, you can quickly learn everything necessary to include the various text components in a program and interact with them on a basic level. For information regarding more complex uses of the various text components, continue with the next section, General Rules for Using Text Components.

This section has five parts:

An Example of Using a Text Field

TextSamplerDemo contains a text field in the upper left corner of the main frame. Here's the code that creates the JTextField.
JTextField textField = new JTextField(10);
textField.setActionCommand(textFieldString);
textField.addActionListener(this);
As with buttons, you can set an action command and register an action listener on a text field. Here's the actionPerformed method implemented by the text field's action listener, which is shared with the program's password field. The actionPerformed method simply copies the text field's contents to a label.
public void actionPerformed(ActionEvent e) {
    String prefix = "You typed \"";
    if (e.getActionCommand().equals(textFieldString)) {
        JTextField source = (JTextField)e.getSource();
        actionLabel.setText(prefix + source.getText() + "\"");
    } else {
        JPasswordField source = (JPasswordField)e.getSource();
        actionLabel.setText(prefix + new String(source.getPassword())
			    + "\"");
    }
}
For descriptions of the JTextField constructor and the getText method used by this demo, refer to How to Use Text Fields. That section also includes information and examples of customized text fields, including how to write a validated field.

An Example of Using a Password Field

JPasswordField is a subclass of JTextField that, instead of showing the actual character the user types, shows another character such as an asterisk '*'. This type of field is useful for prompting users to enter passwords when logging in or validating their identity. Here's the code from TextSamplerDemo that creates the password field and registers an action listener on it:
JPasswordField passwordField = new JPasswordField(10);
passwordField.setActionCommand(passwordFieldString);
passwordField.addActionListener(this);
This code is the similar to that used to create the text field. The password field shares the text field's action listener, which uses these three lines of code to copy the password field's content to a label:
String prefix = "You typed \"";
...
JPasswordField source = (JPasswordField)e.getSource();
actionLabel.setText(prefix + new String(source.getPassword())
		    + "\"");
Notice that this code uses the getPassword method to get the contents of the password field instead of getText. Providing a Password Field explains why and provides additional information about password fields. Remember that password fields are text fields, so the information covered in How to Use Text Fields pertains to password fields as well.

Using a Text Area

A text area displays multiple lines of text and allows the user to edit the text with the keyboard and mouse. Here's TextSamplerDemo's code that creates its JTextArea:
JTextArea textArea = new JTextArea(5, 10);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setText(
    "This is an editable JTextArea " +
    "that has been initialized with the setText method. " +
    "A text area is a \"plain\" text component, " +
    "which means that although it can display text " +
    "in any font, all of the text is in the same font."
);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane areaScrollPane = new JScrollPane(textArea);
areaScrollPane.setVerticalScrollBarPolicy(
		JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setPreferredSize(new Dimension(250, 250));
areaScrollPane.setBorder(/*...create border...*/);
The constructor used in this example to create the text area is similar to those used to create the text field and password field. The text area constructor requires two integer arguments: the number of rows and the number of columns in the text area. These numbers are used to calculate the text area's preferred size. As with the column parameter for fields, think of these numbers as hints.

Next the code set the text area's font followed by the text area's initial text. As the text area's initial text says, that although a text area can display text in any font, all of the text is in the same font.

The next two statements deal with line wrapping. The first is a call to setLineWrap, which turns line wrapping on. By default, a text area doesn't wrap lines. Instead it shows all the text on one line, and if the text area is within a scroll pane, allows itself to be scrolled horizontally. The second is a call to setWrapStyleWord, which tells the text area to wrap lines between words.

The next bit of code creates a scroll pane, puts the text area in it, sets the scroll pane's preferred size, and establishes the scroll pane's borders. A text area is typically managed by a scroll pane. If you put a text area in a scroll pane, be sure to set the scroll pane's preferred size, rather than the text area's preferred size. [PENDING: why is this so?]

This section is the only section about using a text area provided by this tutorial because JTextArea is a straightforward class to use. If you are interested in customizing a text area, you can apply what you learn in General Rules about Using Text Components. Be sure to check the Summary of Text section for relevant API and other examples that use JTextArea.

Using an Editor Pane to Display Text from a URL

JEditorPane is the foundation for Swing's styled text components. TextSamplerDemo uses an editor pane like many programs do: to display uneditable help information initialized from a URL that points to an HTML file, TextSamplerDemoHelp.html.

Here's the code that creates the editor pane in TextSamplerDemo:

JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
...create a URL object for the TextSamplerDemoHelp.html file...
try {
    editorPane.setPage(url);
} catch (IOException e) {
    System.err.println("Attempted to read a bad URL: " + url);
}
The code uses the default constructor to create the editor pane, then calls setEditable(false) so the user cannot edit the text. Next, the code creates the URL object, and calls the setPage method with it. The setPage method opens the resource pointed to by the URL and figures out the format of the text (which in the example is HTML). If the text format is known, the editor pane initializes itself with the text found at the URL.

The code that creates the URL is missing from the above code sample and is interesting in and of itself. Here it is:

String s = null;
try {
    s = "file:"
	+ System.getProperty("user.dir")
	+ System.getProperty("file.separator")
	+ "TextSamplerDemoHelp.html";
    URL helpURL = new URL(s);
    /* ...  use the URL to initialize the editor pane  ... */
} catch (Exception e) {
    System.err.println("Couldn't create help URL: " + s);
}
This code uses system properties to compute a file URL for the help file. Because of the security restrictions implemented by most browsers, this code won't work in applets. Instead, use the applets codebase to compute an http URL.

Like text areas, editor panes are typically managed by a scroll pane:

JScrollPane editorScrollPane = new JScrollPane(editorPane);
editorScrollPane.setVerticalScrollBarPolicy(
		JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
editorScrollPane.setPreferredSize(new Dimension(250, 150));
Note that the scroll pane's preferred size is set, not the editor pane's.

This short section shows a typical and basic use of editor panes. However, many programs need to use editor panes in more sophisticated ways. To learn more, first read the next section, General Rules for Using Text Components, then proceed to How to Use Editor Panes and Text Panes.

An Example of Using a Text Pane

The final text component in our basics tour is JTextPane, which is a JEditorPane subclass. Here's code from TextSamplerDemo that creates and initializes a text pane.
JTextPane textPane = new JTextPane();
String[] initString =
	{ /* ...  fill array with initial text  ... */ };

String[] initStyles =
	{ /* ...  fill array with names of styles  ... */ };

//Create the styles we need
initStylesForTextPane(textPane);

Document doc = textPane.getDocument();

//Load the text pane with styled text
try {
    for (int i=0; i < initString.length; i++) {
	textPane.setCaretPosition(doc.getLength());
	doc.insertString(doc.getLength(), initString[i],
			 textPane.getStyle(initStyles[i]));
	textPane.setLogicalStyle(textPane.getStyle(initStyles[i]));
    }
} catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text.");
}
Briefly, this code hard-codes the initial text into an array and creates and hard-codes several styles--objects that represent different paragraph and character formats--into another array. Next, the code loops over the arrays, inserts the text into the text pane, and specifies the style to use for the inserted text.

Although this makes for an interesting example and concisely shows off several features of JTextPane, "real-world" programs aren't likely to initialize a JTextPane this way. Instead, a production-quality program would apply a bootstrapping process, whereby a basic JTextPane would be used to create and save a document, which could then be read into the JTextPane as the program is developed.

This section showed the code used by TextSamplerDemo to create its text pane, but doesn't describe anything. For details about text panes and useful information about when to use a text pane versus when to use an editor pane, read How to Use Editor Panes and Text Panes. (But only after you're comfortable with the information in General Rules for Using Text Components.)


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Swing Components