The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > Styles  [9 examples]

e1012. Retaining the Logical Style When Setting a New Paragraph Style

Logical styles are a collection of attributes that apply after the attributes of the paragraph style are applied. A common misconception of logical and paragraph styles is that they are independent. That is, setting a new logical style does not affect the current paragraph style and vice versa.

However, a logical style is nothing more than the parent of a paragraph style. If you replace the paragraph style, the logical style is replaced or removed as well. If you set a new logical style, the current parent of the current paragraph style (if any), is replaced with the new logical style.

In order to retain the logical style when setting a new paragraph style in non-replace mode, it is necessary to get the current logical style and restore it after setting the new paragraph style.

    JTextPane textPane = new JTextPane();
    
    // Set logical style
    Style style = textPane.addStyle(null, null);
    StyleConstants.setForeground(style, Color.red);
    textPane.setLogicalStyle(style);
    // 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);
    // paragraph is now red and bold

 Related Examples
e1006. Highlighting Words in a JTextComponent
e1007. Setting the Font and Color of Text in a JTextPane Using Styles
e1008. Sharing Styles Between JTextPanes
e1009. Listing the Styles Associated with a JTextPane
e1010. Listing the Attributes in a Style
e1011. Using a Popup to Apply Styles to a JTextPane
e1013. Automatically Updating Styled Text When a Style Is Updated
e1014. Determining If a Style Attribute Applies to a Character or the Paragraph

See also: Actions and Key Bindings    Caret and Selection    Events    JEditorPane    JFormattedTextField    JTextArea    JTextComponent    JTextField    JTextPane   


© 2002 Addison-Wesley.