Search code examples
javahtmlswingjtextarea

Making a single line bold in a JTextPane without using HTML


I'm trying to bold a single line in my JTextPane, but nothing I do is working. I've tried writing the line with a new, bolded font, but it didn't help.

 Font font = new Font("Consolas", Font.BOLD, 11);
            textPane.setFont(font);
            textPane.setText(textPane.getText() + "\n" + getTimeStamp() + sender + ": " + message);
            textPane.setFont(defaultFont);

How can I do this?


Solution

  • The easiest way to do this, is to get the StyledDocument from the JTextPane, and to use the setCharacterAttributes() method.

    The setCharacterAttributes method on the StyledDocument object allows you to set for a specific character range, a set of attributes, which can include BOLD.

    See the Javadoc for more info

    Some sample code could be

    // set chars 4 to 10 to Bold
    SimpleAttributeSet sas = new SimpleAttributeSet(); 
    StyleConstants.setBold(sas, true);
    textPane.getStyledDocument().setCharacterAttributes(4, 6, sas, false);