Retaining the Logical Style When Setting a New Paragraph Style - Java Java Virtual Machine

Java examples for Java Virtual Machine:Logger

Description

Retaining the Logical Style When Setting a New Paragraph Style

Demo Code

import java.awt.Color;

import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;

public class Main {
  public static void main(String[] args) throws Exception {
    JTextPane textPane = new JTextPane();

    // Set logical style
    Style style = textPane.addStyle(null, null);
    StyleConstants.setForeground(style, Color.red);
    textPane.setLogicalStyle(style);//from ww  w  . ja va  2 s .co  m
    // paragraph is now red

    // Set paragraph style; removes logical style
    style = textPane.addStyle(null, null);
    StyleConstants.setUnderline(style, true);
    textPane.setParagraphAttributes(style, true);
    // paragraph is now underlined, not red

    // Set logical style; replaces paragraph style's parent
    style = textPane.addStyle(null, null);
    StyleConstants.setForeground(style, Color.red);
    textPane.setLogicalStyle(style);
    // paragraph is now red and underlined

    // Get logical style and restore it after new paragraph style
    Style logicalStyle = textPane.getLogicalStyle();
    style = textPane.addStyle(null, null);
    StyleConstants.setBold(style, true);
    textPane.setParagraphAttributes(style, true);
    textPane.setLogicalStyle(logicalStyle);

  }
}

Related Tutorials