4

是否可以在 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);
4

3 回答 3

3

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 );
于 2009-10-29T15:54:07.990 回答
3

更新: 我刚刚发现了一个名为 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"));

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

于 2009-10-29T15:44:45.700 回答
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);
于 2017-07-17T11:35:44.870 回答