Domanda

È possibile cambiare il colore di sfondo di un paragrafo in Java Swing? Ho provato a impostarlo usando il metodo setParagraphAttributes (codice sotto) ma non sembra funzionare.

    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);
È stato utile?

Soluzione

UPDATE: Ho appena scoperto una classe chiamata Evidenziatore, ma non credo che dovresti usare lo stile setbackground. Utilizzare invece la classe DefaultHighlighter.

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

I primi due parametri del metodo addHighlight non sono altro che l'indice iniziale e l'indice finale del testo che si desidera evidenziare. È possibile chiamare questo metodo in modo che più tempi evidenzino righe di testo discontinue.

RISPOSTA VECCHIA:

Non ho idea del perché il metodo setParagraphAttributes non sembra funzionare. Ma farlo sembra funzionare.

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

Forse puoi aggirare questo problema per ora ...

Altri suggerimenti

Uso:

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

Quindi puoi modificare gli attributi esistenti usando:

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

O aggiungi attributi con testo:

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

Modo semplice per cambiare il colore di sfondo del testo o del paragrafo selezionato.

  //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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top