Advertisement
Guest User

Untitled

a guest
Jul 17th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. StyledDocument doc = textPanel.getStyledDocument();
  2. Style style = textPanel.addStyle("Hightlight background", null);
  3. StyleConstants.setBackground(style, Color.red);
  4.  
  5. Style logicalStyle = textPanel.getLogicalStyle();
  6. doc.setParagraphAttributes(textPanel.getSelectionStart(), 1, textPanel.getStyle("Hightlight background"), true);
  7. textPanel.setLogicalStyle(logicalStyle);
  8.  
  9. Highlighter h = textPanel.getHighlighter();
  10. h.addHighlight(1, 10, new DefaultHighlighter.DefaultHighlightPainter(
  11. Color.red));
  12.  
  13. doc.insertString(0, "Hello World", textPanel.getStyle("Hightlight background"));
  14.  
  15. SimpleAttributeSet background = new SimpleAttributeSet();
  16. StyleConstants.setBackground(background, Color.RED);
  17.  
  18. doc.setParagraphAttributes(0, doc.getLength(), background, false);
  19.  
  20. doc.insertString(doc.getLength(), "nEnd of text", background );
  21.  
  22. //choose color from JColorchooser
  23. Color color = colorChooser.getColor();
  24.  
  25. //starting position of selected Text
  26. int start = textPane.getSelectedStart();
  27.  
  28. // end position of the selected Text
  29. int end = textPane.getSelectionEnd();
  30.  
  31. // style document of text pane where we change the background of the text
  32. StyledDocument style = textPane.getStyledDocument();
  33.  
  34. // this old attribute set of selected Text;
  35. AttributeSet oldSet = style.getCharacterElement(end-1).getAttributes();
  36.  
  37. // style context for creating new attribute set.
  38. StyleContext sc = StyleContext.getDefaultStyleContext();
  39.  
  40. // new attribute set with new background color
  41. AttributeSet s = sc.addAttribute(oldSet, StyleConstants.Background, color);
  42.  
  43. // set the Attribute set in the selected text
  44. style.setCharacterAttributes(start, end- start, s, true);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement