在JTextPane(Java Swing)中更改段落的背景颜色

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

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

更新:我刚刚发现了一个名为Highlighter的类。我不认为你应该使用setbackground风格。 请改用DefaultHighlighter类。

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

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

老答案:

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

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

也许你现在可以解决这个问题……

我用:

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

然后您可以使用以下方法更改现有属

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

或者使用文本添加属性:

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

更改所选文本或段落的背景颜色的简便方法。

  //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);