Alterar a cor de um parágrafo de fundo em JTextPane (Java Swing)
-
10-07-2019 - |
Pergunta
É possível alterar a cor de um parágrafo no Java Swing fundo? Eu tentei configurá-lo usando o método setParagraphAttributes (código abaixo), mas não parece trabalho.
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);
Solução
UPDATE: Eu só descobri sobre uma classe chamada Highlighter.I não acho que você deve estar usando o estilo setBackground. Use a classe DefaultHighlighter vez.
Highlighter h = textPanel.getHighlighter();
h.addHighlight(1, 10, new DefaultHighlighter.DefaultHighlightPainter(
Color.red));
Os dois primeiros parâmetros do método addHighlight são nada, mas o índice de início e término do índice do texto que deseja realçar. Você pode chamar esse método múltipla timesto destaque linhas descontínuas de texto.
velha resposta:
Eu não tenho idéia por que os setParagraphAttributes método não parece trabalho. Mas fazer isso parece funcionar.
doc.insertString(0, "Hello World", textPanel.getStyle("Hightlight background"));
Talvez você pode trabalhar um hack em torno deste por agora ...
Outras dicas
Eu uso:
SimpleAttributeSet background = new SimpleAttributeSet();
StyleConstants.setBackground(background, Color.RED);
Em seguida, você pode alterar os atributos existentes usando:
doc.setParagraphAttributes(0, doc.getLength(), background, false);
ou adicionar atributos com texto:
doc.insertString(doc.getLength(), "\nEnd of text", background );
Fácil maneira de mudar a cor do texto ou parágrafo selecionado fundo.
//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);