JavaEnterprise JavaSwingin' Java: Doing it in style

Swingin’ Java: Doing it in style

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


last article, we explained how you can use Swing’s rich array of text components to render either single or multi-line text in your applications. That was fine, but it lacked style. This week’s tutorial (the last in our miniseries) goes over Swing’s styled text components, JEditorPane and JTextPane, and how to create richly styled text components.

As we mentioned in our last article, JTextField, JTextArea, and JPasswordField all render their text in the same way. You can define a font, a color, and a background color for them, but the combination that you use will be the same throughout the component — you can’t have some of the text in your JtextArea plain and some bold. In order to style different portions of your text component individually, you need to use either of Swing’s two styled text components: JTextPane and JEditorPane. Which one you choose depends on your objectives. Before we get into a discussion of styled text components, it may help to review the differences between JTextPane and JEditorPane.

JeditorPane

JEditorPane is used to render data content such as HTML, RTF, etc. JEditorPane is designed around the concept of a page, or a single source of data. It works very well to display fixed amounts of styled text (a Web page, for instance), but tends to lack functionality for inserting and appending text to its document once set.

JTextPane is much more malleable than JEditorPane in terms of the insertion and appending of text, but it is not quite as easy to use. In order to use a JTextPane, you need to associate an attribute set with each of the pieces of text that you insert. We’ll discuss attribute sets shortly.

If you want to display an HTML-formatted page or other pre-defined styled content, then JEditorPane is the way to go. To use JEditorPane, you first construct an instance of it. There are a total of four constructors available for the JEditorPane, each specifying different initial data/constraints. For simplicity, we’ll assume that we use the basic, empty constructor:

JEditorPane editor = new JEditorPane().

Once you have a reference to your JEditorPane, you can either set the page to view and rely on the page to set its own content type or explicitly set the content type and then add text into the pane. If you go with the former method, simply use the

setPage(URL url)
method to set the content for the page. This method is useful if you want to have your JEditorPane display a Web page.

As an alternative to the

setPage(Url url)
method, you can explicitly set the content type for your JEditorPane by calling the

setContentType(String type)
method. For a Web page, the argument to this method would be of the form “text/html”. Once the content type is set, you can set the actual content via either the

setPage(Url url)
method or the

setText(String text)
method. If you use the latter, simply pass in formatted HTML text and the JEditorPane will take care of the rest! One thing to note on the use of JEditorPane is that when displaying HTML, it will render small graphical widgets for the head and title sections of the document unless you call

setEditable(false)
, at which point it will hide them.

In many cases the functionality of JEditorPane will be all that you need for your application. To be sure, it’s a large improvement on anything that existed in Java before Swing. There will be times, however, when this just isn’t enough. That is when you want to haul out the big gun: JTextPane.

JtextPane

JTextPane is an extension of JEditorPane that provides all the functionality you would typically expect of a word processor. Using JTextPane, you can display multicolored text, different fonts, and different styles, as well as embed images, and much more. In order to apply styles to its content, JTextPane uses AttributeSets. These could be the subject of a small book in and of themselves; but for the purposes of this article, all you need to understand about them is that they define a group of attributes that can be applied to your text. The attributes of an AttributeSet are set through static methods of the StyleConstants class.

The static methods of the StyleConstants class, which set the attributes of an AttributeSet, are too numerous to list here. For a complete reference, check the Java Swing API. The methods allow you to set anything from the indentation and tab spacing to the font size, color, and weight. The methods of the class are relatively easy to use and can be seen in Example 1.

Styling

Before we end up confusing you too much with all this abstract talk of style and AttributeSets, let’s get into an actual example. Example 1 shows how both the JEditorPane is used as well as how to use JTextPane to present some formatted text. Of particular note, Example 1 shows how you can reuse your AttributeSets multiple times through your document.

The basic concepts covered in this article and the examples contained in the code should be enough to get you started down the road to putting style into your application’s text components. As the Swing API develops, we can expect to see further enhancements of what is becoming a truly powerful series of text components.

About the author

Dan Simon is a Sun Certified Java Developer with Osage Systems Group Inc., in Wood Dale, Ill.



Example 1.


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;

public class Example1 extends JFrame{

public Example1() {
super(“Swingin’ Java — Styled Text”);
}

public static void main(String[] args) {
Example1 frame = new Example1();

//first we’ll create a JEditorPane and populate it
JEditorPane editor = new JEditorPane();
//set the content type to HTML
editor.setContentType(“text/html”);
//set the editable to false to hide the head and title tags
editor.setEditable(false);
//let’s create a simple html formatted document to put in the JEditorPane
String editorText = “This is a title“;
//we can do just about any styling that we want…
editorText += “

This is centered text

“;
//yes, tables work too
editorText += “

This is cell 0,0 This is cell 1,0 This is cell 2,0
This is cell 0,1 This is cell 1,1 This is cell 2,1

“;
//and any other tag that adheres to the HTML3.2 specification
editorText += “

This is a heading (h2)

“;
//you get the idea, so we’ll close it off
editorText += ““;
//all we need to do now is set the text into our pane
editor.setText(editorText);

//now let’s create a JTextPane, some AttributeSets, etc
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
//here’s an example of some AttributeSets
SimpleAttributeSet boldItalicRedText = new SimpleAttributeSet();
StyleConstants.setForeground(boldItalicRedText, Color.red);
StyleConstants.setBold(boldItalicRedText, true);
StyleConstants.setItalic(boldItalicRedText, true);

SimpleAttributeSet centeredBlackText = new SimpleAttributeSet();
StyleConstants.setForeground(centeredBlackText, Color.black);
StyleConstants.setAlignment(centeredBlackText, StyleConstants.ALIGN_CENTER);

SimpleAttributeSet largeBlackText = new SimpleAttributeSet();
StyleConstants.setForeground(largeBlackText, Color.black);
StyleConstants.setFontSize(largeBlackText, 32);

//now let’s use them
try {
Document doc = textPane.getDocument();
doc.insertString(doc.getLength(), “This is centered, black text…n”, centeredBlackText);
textPane.setParagraphAttributes(centeredBlackText, true);
doc.insertString(doc.getLength(), “This is bold, italic, red text…n”, boldItalicRedText);
doc.insertString(doc.getLength(), “This is 32 point black text.n”, largeBlackText);
}
catch(BadLocationException exp) {
exp.printStackTrace();
}

//all we need to do now is display our components
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,1));
panel.add(new JScrollPane(editor));
panel.add(new JScrollPane(textPane));
panel.setPreferredSize(new Dimension(400,400));

//now we’ll set the panel as our content pane
frame.setContentPane(panel);

//just to be nice, we’ll shut down when the window is closed
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

frame.pack();
frame.show();
}
}

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories