Translucent panel over AWT component

1k Views Asked by At

I have an AWT component (3rd party library), and I need to mask it by showing a translucent panel over it (alpha of 128 in this case). Is there any way at all to do this? I looked at the "TransparentPanel" class that uses Sun's AWTUtilities class, but that has a limitation of not being able to show pixels with 0 < alpha < 255. Even if it's not a pretty solution, I'm just looking for some way to do this.

2

There are 2 best solutions below

1
On

Maybe a GlassPane with translucent paint can solve this. Here's a simple example:

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GlassFrame extends JComponent
{
    public GlassFrame()
    {
        super();
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g.create();

        Paint p = new GradientPaint(
                0, 0, new Color(200,180,180,200), //Select RGB and Alpha values
                getWidth(), 0, new Color(0,0,0,0)
            );
        g2.setPaint(p);
        g2.fillRect(0, 0, getWidth(), getHeight());

        g2.dispose();
    }

    public static void main(String args[])
    {
        JFrame jf = new JFrame("Simple test");
        jf.add(new JPanel());
        GlassFrame g = new GlassFrame();

        jf.setSize(300,300);
        jf.setVisible(true);

        jf.setGlassPane(g);
        g.setVisible(true);
     }
}
0
On

As far as I know, you cannot do this. What comes closer is to create a screen capture of the AWT component while a swing component is to be shown above, and eventually refresh the screen capture now and then. That means the native component is not really there and cannot be used while in screen capture mode (does not respond to mouse clicks and key events).

This is what one of DJ NativeSwing example does to overlay a Swing PNG image with alpha transparency above an embedded web browser. Check the demo: http://djproject.sourceforge.net/ns