I just faced an interesting thing.
I was changing selected text style. The thing is when I change style for ONE WORD one by one it\'s fine but next if I select a wh
TextComponentDemo, discussed in How to Use Editor Panes and Text Panes, is a good example of how to manage this as well as other text component features.
Addendum: TextComponentDemo relies on pre-defined Action
objects to handle editing tasks. Conveniently, StyledEditorKit contains a series of nested classes that derive from StyledTextAction
. As a concrete example, here's how one might add an AlignmentAction
to the Style
menu of TextComponentDemo
in the method createStyleMenu()
:
protected JMenu createStyleMenu() {
JMenu menu = new JMenu("Style");
Action action = new StyledEditorKit.AlignmentAction(
"left-justify", StyleConstants.ALIGN_LEFT);
action.putValue(Action.NAME, "Left");
menu.add(action);
menu.addSeparator();
...
}
The remaining (arbitrary) alignment action names are defined privately in StyledEditorKit.
Addendum: setCharacterAttributes() is the common routine used by the nested editing actions. It invokes a method of the same name in StyledDocument
, as proposed by @StanislavL.
Addendum: I am unable to reproduce the effect you describe. When I set the color of the selection, the style attributes remain unchanged.
Addendum: The StyledEditorKit
actions work just as well with a JButton
or JToolBar
.
new JButton(new StyledEditorKit.ForegroundAction("Red", Color.red))
Use this.getTextPane().getStyledDocument().setCharacterAttributes()