Java Program to format text in JTextPane



To format text in JTextPane, use the SimpleAttributeSet and StyleConstants class. This allows you to set the style of text, background color, foreground color, etc.

At first, create a new JTextPane −

JTextPane pane = new JTextPane();

Now, use the classes to set the style and color −

SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.black);
StyleConstants.setBackground(attributeSet, Color.orange);

Now, apply the set to the pane −

pane.setCharacterAttributes(attributeSet, true);

The following is an example to format text in JTextPane −

Example

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class SwingDemo {
   public static void main(String args[]) throws BadLocationException {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container container = frame.getContentPane();
      JTextPane pane = new JTextPane();
      SimpleAttributeSet attributeSet = new SimpleAttributeSet();
      StyleConstants.setItalic(attributeSet, true);
      StyleConstants.setForeground(attributeSet, Color.black);
      StyleConstants.setBackground(attributeSet, Color.orange);
      pane.setCharacterAttributes(attributeSet, true);
      pane.setText("Get an overview of the features!");
      JScrollPane scrollPane = new JScrollPane(pane);
      container.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

Output


Advertisements