Michał Tabor
Michał Tabor

Reputation: 2467

StyledDocument's setCharacterAttributes() - get rid of unwanted behaviour

JTextPane pane = new JTextPane();
pane.setText("some text");
add(pane);

pane.addStyle("red", null);
Style red = pane.getStyle("red");
StyleConstants.setForeground(red, Color.RED);
pane.getStyledDocument().setCharacterAttributes(3, 1, red, true);

After this pane's content looks alright: all characters are plain except for 'e' character which is red. But after I input some character after 'e' it gets red too. How do I get rid of this behaviour? I only want to set attributes of given characters and I don't want it to have any impact on others.

Upvotes: 2

Views: 547

Answers (1)

VGR
VGR

Reputation: 44328

Modifying the JTextPane's input attributes should do it:

pane.addCaretListener(new CaretListener() {
    public void caretUpdate(CaretEvent event) {
        final JTextPane textPane = (JTextPane) event.getSource();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                MutableAttributeSet inputAttr =
                    textPane.getInputAttributes();
                inputAttr.removeAttribute(StyleConstants.Foreground);
            }
        });
    }
});

Upvotes: 1

Related Questions