How to create an image map using Java Swing?

2019-03-06 16:10发布

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!

2条回答
爷、活的狠高调
2楼-- · 2019-03-06 16:48

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
查看更多
时光不老,我们不散
3楼-- · 2019-03-06 16:51

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.

查看更多
登录 后发表回答