Search code examples
javaswinguser-interfaceoverlapimageicon

Identify which of three partially overlapping images is clicked


I have several JLabels, each holding an ImageIcon like this:

ImageIcon icon = new ImageIcon("path/to/image.jpg");
JLabel label = new JLabel(icon);

Those images are .PNGs in a hexagonal shape. The edges "outside" the hexagon (the redundant part that exists is using a rectangular canvas) are transparent. The JLabels, ergo the images, are ordered like in this example, so there are always three interfering images.

Since there is no "visible" layer beneath or over an other, I want to define the "clickable area" to exactly the visible layer. What is the cleverest way to do so, or is there an even more elegant solution?


Solution

  • I can think of three solutions for this problem:

    1. If your hexagonal shape is just "black lines" - you can implement paintComponent and paint Polygons. You will have to have the references to them. Later on - on mouse click you will have to get shapes' component and mouse point in it. Then iterate over shapes calling contains for each of them. You will lose layout support using this solution.
    2. Implement GlassPane/layer and dispatch mouse event to appropriate JLabel - iterating over JLabels
    3. This would be least preferable (because of tight coupling) - extend JLabel and add references to adjacent hexagonal components. When mouse click is fired up you check if this component should "catch" this event. If not - you "forward" the event to appropriate component.