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
I think there is no need to subclass of anything. Just use a Jlabel. You can set an image into a Jlabel. So, resize the Jlabel then fill it with an image. Its OK. This is the way I do.
JLabel imgLabel = new JLabel(new ImageIcon("path_to_image.png"));
JPanel
is almost always the wrong class to subclass. Why wouldn't you subclass JComponent
?
There is a slight problem with ImageIcon
in that the constructor blocks reading the image. Not really a problem when loading from the application jar, but maybe if you're potentially reading over a network connection. There's plenty of AWT-era examples of using MediaTracker
, ImageObserver
and friends, even in the JDK demos.
Fred Haslam's way works fine. I had trouble with the filepath though, since I want to reference an image within my jar. To do this, I used:
BufferedImage wPic = ImageIO.read(this.getClass().getResource("snow.png"));
JLabel wIcon = new JLabel(new ImageIcon(wPic));
Since I only have a finite number (about 10) images that I need to load using this method, it works quite well. It gets file without having to have the correct relative filepath.
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()).
You can avoid rolling your own Component subclass completely by using the JXImagePanel class from the free SwingX libraries.
Download