Click here to Skip to main content
15,899,825 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi all. I hope you can help me with this one.

I want to display an image on screen and have a event handler for that image. The problem is that I only want the event handler to work on the part of the image that you can see.

It will be a PNG with a transparent background. Lets use a ball as an example. I only want the event handler to trigger when the user clicks on the ball and not when he clicks right next to the ball.

I know I can create a region around the ball and add the event handler to that but that will take forever since my images is funny shapes and sizes and I have a lot of them.

Is there any way to make this work?
Posted

How to write a MouseListener[^]

That also suits an image, as that is also just a component.


When detecting a certain area in an image, it needs to have a defined thingy on which one can recognize it.
That might be a certain mouse position, a certain color value at that position or, as you already mentioned, an overlay which defines so.

You might get along with the color value. So if you figure, which color is set in the image at the position the mouse event happens...

Have fun!
 
Share this answer
 
Thanks TorstenH for pointing me in the right direction.

I thought I'd post my code if anyone ells needs this one day. Please keep in mind this is only from my test app and it needs some tweeking if you want to use it. This is placed in the mouse click event of the JPanel.

Java
BufferedImage img = null;
		    	
try
{
	img = ImageIO.read(new File("res/1.png"));
}
catch (IOException e1)
{
	e1.printStackTrace();
}
				
int packedInt = 0;
int ha = 1;
packedInt = img.getRGB(e.getX(), e.getY());
Color color = new Color(packedInt, true);
		    	
if (color.getTransparency() == 1)
{
	try
	{
		if (ha == 0)
		{
			img = ImageIO.read(new File("res/1.png"));
			lblNewLabel.setIcon(new ImageIcon("res/1.png"));
			ha = 1;
		}
		else
		{
			img = ImageIO.read(new File("res/2.png"));
			lblNewLabel.setIcon(new ImageIcon("res/2.png"));
			ha = 0;
		}
	}
	catch (Exception ex)
	{
		    			
	}
		    		
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900