Вопрос

Можно ли изменить цвет фона абзаца в 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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top