views:

541

answers:

2

I need to make an image map using Swing that displays a background image, and then when the mouse hovers over (or clicks) specific hotspots, I need to pop up a 'zoomed-in' image and have it display.

I was thinking of extending JPanel to include an image reference and have that drawn thru the paintComponent(g) method. This part I have done so far, and here's the code:

public class ImagePanel extends JPanel
{
    private static final long serialVersionUID = 1L;

    private Image image;

    public ImagePanel(Image image)
    {
        setImage(image);
    }

    public void setImage(Image newImage)
    {
        image = newImage;
    }

    @Override
    public void paintComponent(Graphics g)
    {
        Dimension size = getSize();
        g.drawImage(image, 0, 0, size.width, size.height, this);
    }

Could anyone recommend how I might listen for / respond to mouse clicks over defined hot-spots? Could someone additionally recommend a method for displaying the pop-ups? My gut reaction was to extend JPopupMenu to have it display an image, similar to the above code.

Thanks for any help!

+1  A: 

To listen to the mouse clicks implement the MouseListener interface, and add it to your panel. Then when the click is recieved you can use a JPopupMenu as you suggested, or you could even use a glass pane to show the zoomed in image.

I'm guessing you want to achieve something similar to this post by Joshua Marinacci, he has also posted the source here, I would take a look at that.

broschb
Cool, thank you!
Cuga
+1  A: 

I would probably:

  • create some instance of Shape that represents each of your hotspots (could be a plain boring old Rectangle, or see GeneralPath if you need to create fancy shapes)
  • register a MouseListener which iterates through each of the Shapes and calls its contains() method to see if the clicked coordinate is inside the hotspot in question
Neil Coffey
I'd like to do this, but something I didn't mention is that the hotspots can be arbitrary in an image. So a way around this could be to overlay the sub images, but I'm not sure if I want to do that.
Cuga