Java examples for Swing:JTextPane
Setting the Font and Color of Text in a JTextPane Using Styles
import java.awt.Color; import javax.swing.JTextPane; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; public class Main { public static void main(String[] argv) { 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); }/*from w w w . ja va2 s . c o m*/ }