Search code examples
javaswingjcomponentclickablemouselistener

Java. Swing. JComponent's clickable area


I have a custom component displaying *.png image. The image has transparent and non-transparent area. If I add ActionListener(or MouseClickListener) to component, it will raise events even if I click on transparent area of component. Visually it looks like clicking outside the component. How can I declare which area should react on clicks and which should not?

I've read about getting pixel from image your coordinates from event object and check its transparency. It seems difficult and ineffective.

Maybe define custom-border of this component or something else?


Solution

  • How can I declare which area should react on clicks and which should not?

    This is done at the JComponent level by overriding the contains(...) method. So for example you extend JLabel to create a TransparentLabel which contain your image in the form of an icon.

    Then whenever this method is invoked you only need to check this one location to determine if the pixel is transparent or not.