off-screen images with transparent backgrounds problem
Posted on 2003-03-15
I have some equations that need to be graphed, so I wrote a little class (MyPanel) that extends
JPanel and plots the appropriate points using the Graphics object's drawing methods in
I want MyPanel to be transparent so that the background color of its container could show thru. To that end I did a setOpaque(false) in the constructor. Everything works fine when I plot the points of the equations directly using the Graphics object passed into paintComponent and
call super.paintComponent(g) at the end of MyPanel's paintComponent method.
In the course of things I decided that since there are a LOT of math operations that need to
be done to determine each point to plot, I could make things like scrolling more efficient if I
created an off-screen image buffer that could be created once, with different sections displayed
as the user scrolls. So I used MyPanel's createImage(w,h) method, did an
Graphics ig = image.getGraphics(), plotted the points with ig and then used my original Graphics object's drawImage method to display the off-screen buffer. When I do this the background ends up being gray.
I tried clearing the off-screen image by going setColor(new Color(0,0,0,0)); fillRect(...);
figuring that a transparent color as the background would allow the JPanel's container to show
thru since the JPanel is opaque. But that did not work.
I tried specifying a bgcolor in the drawImage method, but it didn't seem to make any difference
there...I'm not really clear on what that is supposed to do actually since reguardless of the
alpha value of the pixels I draw in the off-screen image, the bgcolor argument to drawImage
seems to be ignored.
I'd prefer a solution that made MyPanel's parent container's background show thru instead of
just clearing the off-screen image to that color.