문제

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라는 수업에 대해 알게되었습니다. 나는 당신이 퇴보 스타일을 사용해야한다고 생각하지 않습니다. 대신 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