Swing: how to know if a pixel of a JComponent is transparent?

Guillaume F. :

Is there a way to tell if the pixel of a JComponent (such as JEditorPane, JPanel, etc) is transparent?

I know that for top-level containers such as JFrame or JDialog, getContentPane().paintAll() can be used to paint the content of the container to a BufferedImage. We can then use getRGB(x,y) to get the color & transparency of the pixel at (x,y).

However, the approach doesn't tell me the color of the individual components. Is there a way to know the pixel colors of low-level containers?

More info:

My purpose for this is to have a JEditorPane behave like a transparent overlay. The JEditorPane can contain text, pictures, etc, but its background is transparent

I'd like the mouse events to be forwarded to the components under the JEditorPane if they happen over a transparent pixel of the JEditorPane, but dealt with differently if the pixel is opaque.

Sergiy Medvynskyy :

You can simply try to modify my previous answer to fit your requirement

public static boolean isTransparent(Component c, Point p) {
    Rectangle rect = c.getBounds();
    BufferedImage img = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_ARGB);
    c.paintAll(img.createGraphics());
    return new Color(img.getRGB(p.x, p.y), true).getAlpha() == 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=373093&siteId=1