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
Post a comment