JTextPane with background color

JTextPane and his ancestors JEditorPane and JTextComponent won't respect the color defined with setBackground(Color) since they display a "styled document" and expect the background color to be defined in the content. You'll always see a white background.

To change the background color (without modifying the content) you have to define attributes for the document:

  1. JTextPane textPane = new JTextPane();
  2. textPane.setContentType("text/html"); // or any other styled content type
  3. textPane.setText("White text on a red background");
  5. textPane.setForeground(Color.white); // Works as expected
  6. textPane.setBackground(Color.red); // Obsolete, no affect
  8. // Define a default background color attribute
  9. Color backgroundColor = Color.red;
  10. StyleConstants.setBackground(background, backgroundColor);
  11. textPane.getStyledDocument().setParagraphAttributes(0,
  12. textPane.getDocument().getLength(), background, false);
  14. // And remove default (white) margin
  15. textPane.setBorder(BorderFactory.createEmptyBorder());
  17. // Alternative: Leave a 2px border but draw it in the same color
  18. textPane.setBorder(BorderFactory.createLineBorder(backgroundColor, 2));


This doesnt appear to work either, I presume this is to get the background color to show in the editor?

Add new comment