Change text style to bold, italic and set text color in Java

Description

The following code shows how to change text style to bold, italic and set text color.

Example


import java.awt.BorderLayout;
import java.awt.Color;
//from w  ww  . java2  s.  com
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Main {
  public static void main(String args[]) throws Exception{
    JFrame frame = new JFrame("Simple Attributes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    StyledDocument document = new DefaultStyledDocument();

    SimpleAttributeSet attributes = new SimpleAttributeSet();
    attributes.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.FALSE);
    attributes.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.FALSE);
    attributes.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.LIGHT_GRAY);

    document.insertString(document.getLength(), "java2s.com", attributes);

    JTextPane textPane = new JTextPane(document);
    textPane.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textPane);

    frame.add(scrollPane, BorderLayout.CENTER);

    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Change text style to bold, italic and set text color in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform