Setting the Font and Color of Text in a JTextPane Using Styles

A style is a set of text attributes, such as font size and color. A style can be applied any number of times to the contents of a text pane. When a style is applied to a word in the text pane, the style is not associated with the word. Rather, the contents of the style, namely the attributes, are associated with the word. This means that if the style is changed, the set of attributes associated with the word does not change.

Styles can be stored in a text pane so that they can be retrieved, modified, and applied later. It is not necessary for a style to be stored with a text pane in order to use the style on the text pane.

This example demonstrates the creation and application of styles in the contents of a JTextPane. See StyleConstants for a complete set of available attributes.

JTextPane textPane = new JTextPane(); StyledDocument doc = textPane.getStyledDocument(); // Makes text red Style style = textPane.addStyle("Red", null); StyleConstants.setForeground(style, Color.red); // Inherits from "Red"; makes text red and underlined style = textPane.addStyle("Red Underline", style); StyleConstants.setUnderline(style, true); // Makes text 24pts style = textPane.addStyle("24pts", null); StyleConstants.setFontSize(style, 24); // Makes text 12pts style = textPane.addStyle("12pts", null); StyleConstants.setFontSize(style, 12); // Makes text italicized style = textPane.addStyle("Italic", null); StyleConstants.setItalic(style, true); // A style can have multiple attributes; this one makes text bold and italic style = textPane.addStyle("Bold Italic", null); StyleConstants.setBold(style, true); StyleConstants.setItalic(style, true); // Set text in the range [5, 7) red doc.setCharacterAttributes(5, 2, textPane.getStyle("Red"), true); // Italicize the entire paragraph containing the position 12 doc.setParagraphAttributes(12, 1, textPane.getStyle("Italic"), true);

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.