2009-10-29 137 views
4

是否可以在Java Swing中更改段落的背景颜色?我试图使用setParagraphAttributes方法(下面的代码)来设置它,但似乎不起作用。更改JTextPane中段落的背景颜色(Java Swing)

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); 
+0

请注意,使用特定背景颜色设置段落元素属性(正确)将仅影响该段落的字符。它不会影响该段落右侧(或左侧)的空间。然而,可以为JTextComponent的Highlighter提供一个自定义的'Highlighter.HighlightPainter'来做到这一点。 –

回答

3

UPDATE: 我只是发现了一类名为Highlighter.I不认为你应该使用的setBackground风格。改为使用DefaultHighlighter类。

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

addHighlight方法的前两个参数不过是要突出显示的文本的起始索引和结束索引。您可以多次调用此方法突出显示不连续的文本行。

OLD答:

我不知道为什么似乎没有了setParagraphAttributes方法工作。但这样做似乎有效。

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

也许你可以工作一个黑客解决这个现在...

+0

感谢您的回复。上面的代码可以工作,但它只会改变背景颜色,如果文本存在。我想要改变背景颜色,即使文本不存在。 (像CSS中的背景颜色属性) – Sudar

+0

您指定您正在改变CSS背景颜色的标签。你会在jtextpane中做什么?问题是,你必须为你划定一段文字并设定颜色不是?您可以指定字符(或者预先指定的像素区域),也可以指定整个窗格。 或使用JEditorPane,我认为CSS在JEditorPane中工作... – Jaskirat

+0

顺便说一句,刚刚尝试过CSS,甚至在CSS中,你不能在段落中没有任何文本的bgcolor。不知道究竟你的意思是...... 我想这 ' <风格类型= “文/ CSS”> p {背景色:RGB(255,0,255);}

这是一个段落。

下面对犯规含有所以它不是强调任何文字...

' – Jaskirat

3

我用:

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

然后你可以使用改变现有的属性:

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

或者用文字添加属性:

doc.insertString(doc.getLength(), "\nEnd of text", background); 
+0

我不想整个文本窗格着色。我只想要一段颜色。我尝试了你的方法,它似乎并没有工作。 – Sudar

+0

当然可以。所有你需要做的是改变开始,长度值。这是读取API以了解每种方法的参数如何工作。 – camickr

0

简单的方法来改变选定的文本或段落的背景颜色。

//choose color from JColorchooser 
    Color color = colorChooser.getColor(); 

    //starting position of selected Text 
    int start = textPane.getSelectedStart(); 

    // end position of the selected Text 
    int end = textPane.getSelectionEnd(); 

    // style document of text pane where we change the background of the text 
    StyledDocument style = textPane.getStyledDocument(); 

    // this old attribute set of selected Text; 
    AttributeSet oldSet = style.getCharacterElement(end-1).getAttributes(); 

    // style context for creating new attribute set. 
    StyleContext sc = StyleContext.getDefaultStyleContext(); 

    // new attribute set with new background color 
    AttributeSet s = sc.addAttribute(oldSet, StyleConstants.Background, color); 

// set the Attribute set in the selected text 
    style.setCharacterAttributes(start, end- start, s, true);