Friday, October 8, 2010

How to Make a JTextPane / StyledDocument TRULY Transparent

It's been a long time since my last update; I wanted to share with you a solution that took me weeks to get:

Q: How can I make a Java Swing JTextPane component (including text background) transparent?

A: textPane.setBackground(new Color(255, 255, 255, 0)) ; <- Set a background Color with a 0 alpha value (a 100% transparent color).

In my case, using textPane.setOpaque(false) didn't work, and I tried EVERYTHING trying to understand why, and get around it. I blamed the StyledDocument believing the text or paragraph included a background color, I blamed the component layers and their blending, I browsed over a lot of forums and pages; no one gave me a working solution.

I tried overriding paintComponent and setting an Icon property for the text but both draw the image above the text.

I hope this is useful for people who, just like me, can't understand WHY IN THE WORLD the setOpaque method does not always work on a JTextPane with a styled text. I still don't know why.

If someone out there is as wise as to have the answer, it would be nice to know, for know there's the solution to make it work. ;-)

See you later!