Tag Archives: HiLighted text

HiLighting words in a JTextPane


This example shows how text can be HiLighted in the text of a JTextPane.

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);