Java Program to insert styled text in a JTextPane Component

Java 8Object Oriented ProgrammingProgramming

Insert styled text in a JTextPane component using the SimpleAttributeSet and StyleConstants classes. With that, we will also use StyledDocument.

The following is an example to insert styled text in a JTextPane component −

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
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.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
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 textPane = new JTextPane();
      textPane.setForeground(Color.blue);
      textPane.setBackground(Color.cyan);
      SimpleAttributeSet set = new SimpleAttributeSet();
      StyleConstants.setItalic(set, true);
      textPane.setCharacterAttributes(set, true);
      textPane.setText("This is our text pane! ");
      Font font = new Font("Verdana", Font.BOLD, 18);
      textPane.setFont(font);
      StyledDocument doc = (StyledDocument) textPane.getDocument();
      Style style = doc.addStyle("StyleName", null);
      StyleConstants.setBold(style, true);
      doc.insertString(doc.getLength(), "Demo text", style);
      JScrollPane scrollPane = new JScrollPane(textPane);
      scrollPane = new JScrollPane(textPane);
      container.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

Output

raja
Published on 03-Jun-2019 12:46:07
Advertisements