![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e1007. Setting the Font and Color of Text in a JTextPane Using StylesA 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 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);
e1008. Sharing Styles Between JTextPanes e1009. Listing the Styles Associated with a JTextPane e1010. Listing the Attributes in a Style e1011. Using a Popup to Apply Styles to a JTextPane e1012. Retaining the Logical Style When Setting a New Paragraph Style e1013. Automatically Updating Styled Text When a Style Is Updated e1014. Determining If a Style Attribute Applies to a Character or the Paragraph
© 2002 Addison-Wesley. |