How to create an image map using Java Swing?

跟風遠走 提交于 2019-12-31 07:29:08

问题


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:


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.




回答2:


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


来源:https://stackoverflow.com/questions/1537932/how-to-create-an-image-map-using-java-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!