JTextPane - a phrase with TWO styles

前端 未结 2 1788
轻奢々
轻奢々 2020-12-07 01:36

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

相关标签:
2条回答
  • 2020-12-07 02:18

    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))
    

    TextComponentDemo

    0 讨论(0)
  • 2020-12-07 02:23

    Use this.getTextPane().getStyledDocument().setCharacterAttributes()

    0 讨论(0)
提交回复
热议问题