How to add text different color on JTextPane

This will print out “BLAH BLEG” in two different colors. public class Main { public static void main(String[] args) { JTextPane textPane = new JTextPane(); StyledDocument doc = textPane.getStyledDocument(); Style style = textPane.addStyle(“I’m a Style”, null); StyleConstants.setForeground(style, Color.red); try { doc.insertString(doc.getLength(), “BLAH “,style); } catch (BadLocationException e){} StyleConstants.setForeground(style, Color.blue); try { doc.insertString(doc.getLength(), “BLEH”,style); } catch … Read more

JTextPane formatting [closed]

Also seen here, TextComponentDemo shows how to apply a number of StyleConstants, including font size, style, alignment and color. The styles may applied either directly to the Document, as shown in initAttributes(), or via the actions of StyledEditorKit, seen here. Addendum: The example below creates three related styles using SimpleAttributeSet. Note that highAlert alters the … Read more

Centering Text in a JTextArea or JTextPane – Horizontal Text Alignment

You need to use a JTextPane and use attributes. The following should center all the text: StyledDocument doc = textPane.getStyledDocument(); SimpleAttributeSet center = new SimpleAttributeSet(); StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER); doc.setParagraphAttributes(0, doc.getLength(), center, false); Edit: Vertical centering is not supported as far as I know. Here is some code you might find useful: Vertical Alignment of JTextPane

How to change the color of specific words in a JTextPane?

No. You are not supposed to override the paintComponent() method. Instead, you should use StyledDocument. You should also delimit the words by your self. Here is the demo, which turns “public”, “protected” and “private” to red when typing, just like a simple code editor: import javax.swing.*; import java.awt.*; import javax.swing.text.*; public class Test extends JFrame … Read more

Keeping the correct style on text retrieval

The text is already formatted on the input JTextPane . What i need to do is transfer it as it is on a different JTextPane without having to check the different style options example import java.awt.*; import javax.swing.*; import javax.swing.text.*; public class Fonts implements Runnable { private String[] fnt; private JFrame frm; private JScrollPane jsp; … Read more