質問

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メソッドの最初の2つのパラメーターは、強調表示するテキストの開始インデックスと終了インデックスにすぎません。このメソッドを複数回呼び出して、不連続なテキスト行を強調表示できます。

古い回答:

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