How to add an image to a JPanel?

前端 未结 14 1730
陌清茗
陌清茗 2020-11-22 00:01

I have a JPanel to which I\'d like to add JPEG and PNG images that I generate on the fly.

All the examples I\'ve seen so far in the Swing Tutorials, specially in the

14条回答
  •  萌比男神i
    2020-11-22 00:50

    I'm doing something very similar in a private project I'm working on. Thus far I've generated images up to 1024x1024 without any problems (except memory) and can display them very quickly and without any performance problems.

    Overriding the paint method of JPanel subclass is overkill and requires more work than you need to do.

    The way I do it is:

    Class MapIcon implements Icon {...}
    

    OR

    Class MapIcon extends ImageIcon {...}
    

    The code you use to generate the image will be in this class. I use a BufferedImage to draw onto then when the paintIcon() is called, use g.drawImvge(bufferedImage); This reduces the amount of flashing done while you generate your images, and you can thread it.

    Next I extend JLabel:

    Class MapLabel extends Scrollable, MouseMotionListener {...}
    

    This is because I want to put my image on a scroll pane, I.e. display part of the image and have the user scroll around as needed.

    So then I use a JScrollPane to hold the MapLabel, which contains only the MapIcon.

    MapIcon map = new MapIcon (); 
    MapLabel mapLabel = new MapLabel (map);
    JScrollPane scrollPane = new JScrollPane();
    
    scrollPane.getViewport ().add (mapLabel);
    

    But for your scenario (just show the whole image every time). You need to add the MapLabel to the top JPanel, and make sure to size them all to the full size of the image (by overriding the GetPreferredSize()).

提交回复
热议问题