Search code examples
javaswingjpanelopacitygetcolor

How to get the color beneath an opaque JPanel?


Is there is a way to get the color underneath an opaque JPanel?

I have two JPanels, a red one and a blue one (they are animated). I want to get the color of a surface according to the JPanel that passes over it.

In following images, the small borderd square is an opaque JPanel, and I want to retrieve the color of the JPanel beneath.

https://i.sstatic.net/45YQV.png

https://i.sstatic.net/EXKmN.png


Solution

  • Not really sure what you are asking. But assuming you know the x/y location of the rectangle you could use:

    1. The getComponentAt(...) method of the Container class. Once you get the parent panel you use the getBackground()` method to get the Color

    2. Or, you can use the Robot class and the getPixelColor(...)` method.