views:

798

answers:

2

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);
+1  A: 

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

Jass
Thanks for the reply. The above code works, but it changes the background color only, if the text is present. I want the background color to be changed, even if the text is not present. (Like the background color property in CSS)
Sudar
You specify the tag you are altering the background color of in css. What would you do in a jtextpane? The question is , you have to figure of what demarcates a paragraph for you and set the color no? You can either specify the characters(or predesignated pixel areas if you want) or the whole pane.Or use JEditorPane, I think CSS works in JEditorPane...
Jass
BTW just tried css and even in css you cant have bgcolor without any text in the para. Dunno what exactly you mean... I tried this `<html><head> <style type="text/css"> p{background-color:rgb(255,0,255);} </style> </head> <p>This is a paragraph.</p> The below para doesnt contain any text so its not highlighted... <p></p> </body></html>`
Jass
+1  A: 

I use:

SimpleAttributeSet background = new SimpleAttributeSet();
StyleConstants.setBackground(background, Color.RED);

Then you can change existing attributes using:

doc.setParagraphAttributes(0, doc.getLength(), background, false);

Or add attributes with text:

doc.insertString(doc.getLength(), "\nEnd of text", background );
camickr
I don't want the entire text pane to be colored. I want only one paragraph to be colored. I tried your approach and it doesn't seem to work.
Sudar
Sure it does. All you need to do is change the start, length values. That is read the API to understand how the parameters for each method work.
camickr