Yegoshin Maxim
Yegoshin Maxim

Reputation: 881

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?

Upvotes: 4

Views: 3915

Answers (4)

herpderp
herpderp

Reputation: 11

If your main issue about "overhead" is that you only want to make it opaque when the mouse enters a non-transparent part of the image, I'd consider pre-computing an image "mask".

On image load, make another image (or a 2d array, or something similar) that will be binary (i.e. black-and-white only, or 1 and 0 values only in an array). 0/white = transparent, 1/black = non-transparent.

Then, on mouse events, you can just check the exact pixel in the mask if it is set (value = black or 1), and trigger if it is.

Upvotes: 1

camickr
camickr

Reputation: 324147

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.

Upvotes: 2

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51553

You answered your own question.

Within the mousePressed() event handler, you're going to have to check if you're within the JComponent, and then check the pixel at the x and y coordinate of the mouse click for transparency.

Upvotes: 3

blue_diamond
blue_diamond

Reputation: 65

Did you try to bunk two same pictures file and just for the second picture give it a short width ? Like that I think you will can to add differents listerners for the both pictures.

Upvotes: 0

Related Questions