Search code examples
javaswingawtrenderinggraphics2d

Buffer Strategy with Per-pixel Transparency


Viewing this I thought I understood per-pixel transparency, however when replacing the JPanel with a Canvas, then replacing the rendering method with a buffer strategy, I cannot obtain per-pixel transparency.

window.setBackground(new java.awt.Color(0, 0, 0, 0));

in combination with

canvas.setBackground(new java.awt.Color(0, 0, 0, 0));

while using the standard overriding of the paint method, works like a charm. However when using the more ideal, buffer strategy:

....
        Graphics2D g = null;
        try {
            g = (Graphics2D) strategy.getDrawGraphics();
            renderer.render(this, g, getWidth(), getHeight());
        } finally {
            g.dispose();
        }
        strategy.show();
....

I need to comment out

window.setBackground(new java.awt.Color(0, 0, 0, 0));

And I loose the ability to paint transparent pixels, (Completely transparent background).

Is there something I am missing here?


Solution

  • If you are talking about java.awt.Canvas then, probably, this is your problem. You are not supposed to mix Canvas with Swing applications (although there are still some components from awt that we use in Swing apps like the events for example).

    If you create a JFrame with a menubar and instead of a JPanel you use a Canvas as the middle component, when you click on the menu the menu is rendered under the Canvas and you cannot see the menuitems. So, probably, you are having this issue due to the Canvas not supporting this feature.