Search code examples
javaswingjtextpane

Bold text in JTextPane


I want to have buttons for html tags and highlighting the text, i start with
tag:

    @Override
    public void actionPerformed(ActionEvent e) {

        SimpleAttributeSet sas = new SimpleAttributeSet();
        StyleConstants.setBold(sas, true);
        insertText(getCaretPosition(), "<br>");
        helpTextPane.getStyledDocument().setCharacterAttributes(getInputTextLenght() - 4, getInputTextLenght(), sas, false);
        StyleConstants.setBold(sas, false);
    }

the output is as follows: enter image description here and i totally do not know why every second time the text inside the br tag is bold :/ I want to have only html br tag bold, no the text inside the tag.


Solution

  • StyledDocument's method

    public void setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace)
    

    The second param should be length

    So try

    setCharacterAttributes(getInputTextLenght() - 4, 4, sas, false);