Question

Est-il possible de changer la couleur d'arrière-plan d'un paragraphe dans Java Swing? J'ai essayé de le définir à l'aide de la méthode setParagraphAttributes (code ci-dessous) mais ne semble pas fonctionner.

    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);
Était-ce utile?

La solution

MISE À JOUR: Je viens de découvrir une classe appelée Highlighter. Je ne pense pas que vous devriez utiliser le style setbackground. Utilisez plutôt la classe DefaultHighlighter.

Highlighter h = textPanel.getHighlighter();
h.addHighlight(1, 10, new DefaultHighlighter.DefaultHighlightPainter(
            Color.red));

Les deux premiers paramètres de la méthode addHighlight ne sont rien d'autre que l'index de départ et l'index de fin du texte que vous souhaitez surligner. Vous pouvez appeler cette méthode plusieurs fois pour mettre en évidence des lignes de texte discontinues.

ANCIENNE RÉPONSE:

Je ne sais pas pourquoi la méthode setParagraphAttributes ne semble pas fonctionner. Mais cela semble fonctionner.

    doc.insertString(0, "Hello World", textPanel.getStyle("Hightlight background"));

Peut-être que vous pouvez vous en occuper pour le moment ...

Autres conseils

j'utilise:

SimpleAttributeSet background = new SimpleAttributeSet();
StyleConstants.setBackground(background, Color.RED);

Vous pouvez ensuite modifier les attributs existants à l'aide de:

doc.setParagraphAttributes(0, doc.getLength(), background, false);

Ou ajoutez des attributs avec du texte:

doc.insertString(doc.getLength(), "\nEnd of text", background );

Moyen facile de changer la couleur de fond du texte ou du paragraphe sélectionné.

  //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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top