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

我们两清 提交于 2020-01-02 05:34:14

问题


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:


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




回答2:


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



回答3:


Easy way to change the background color of selected text or paragraph.

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


来源:https://stackoverflow.com/questions/1642725/changing-the-background-color-of-a-paragraph-in-jtextpane-java-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!