javaswingcolorsbackgroundjtextpane

Changing the background color of a paragraph in JTextPane (Java Swing)


Is it possible to change the background color of a paragraph in Java Swing? I tried to set it using the setParagraphAttributes method (code below) but doesn't seem to work.

    StyledDocument doc = textPanel.getStyledDocument();
    Style style = textPanel.addStyle("Hightlight background", null);
    StyleConstants.setBackground(style, Color.red);

    Style logicalStyle = textPanel.getLogicalStyle();
    doc.setParagraphAttributes(textPanel.getSelectionStart(), 1, textPanel.getStyle("Hightlight background"), true);
    textPanel.setLogicalStyle(logicalStyle);

Solution

  • UPDATE: I just found out about a class called Highlighter.I dont think you should be using the setbackground style. Use the DefaultHighlighter class instead.

    Highlighter h = textPanel.getHighlighter();
    h.addHighlight(1, 10, new DefaultHighlighter.DefaultHighlightPainter(
                Color.red));
    

    The first two parameters of the addHighlight method are nothing but the starting index and ending index of the text you want to highlight. You can call this method multiple timesto highlight discontinuous lines of text.

    OLD ANSWER:

    I have no idea why the setParagraphAttributes method doesnt seem to work. But doing this seems to work.

        doc.insertString(0, "Hello World", textPanel.getStyle("Hightlight background"));
    

    Maybe you can work a hack around this for now...