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!

4 comments:

gumuruhsspj said...

Yeah, I just done setting up
my Swing with a transparent JTextPane

here I got the tips;

1) SetOpaque false
2) SetThe color background to Active Caption Border (using netbeans)

obtained from:
http://java-puzzle.blogspot.com/2009/09/how-to-make-jtextarea-transparent-in.html

UnknownFact said...

Sadly enough, this is not working for me. I have tried with a JTextArea and a JTextPane, and nothing. I've tried with, in addition to setOpaque(false), setBackground(new Color(255, 255, 255, 0)), setBackground(new Color(0,0,0,0)), using an opaque(false) panel or not and it isn't working.

Thing is I'm trying to do this on a JFrame with an overridden Paint method that paints a .jpg.


Anonymous said...

TY! It works for me.
Maybe the result depends by L&F used and/or JRE version. I'm using
- Nimbus L&F
- JRE 1.7

stuchl4n3k said...

Thank you, I owe you one! setOpaque itself did not work for me either...