Hi,
I've got a problem: I want to write an application with 6 JButtons.
Clicking on each JButton should display an appriopriate image. Images
are .jpg files (1000x1000 pixels).
Now, I've got something like that:
URL img1Url, img2Url, img3Url, img4Url, img5Url, img6Url;
JLabel img1, img2, img3, img4, img5, img6;
img1Url = getClass().getResource("img1.jpg");
img2Url = getClass().getResource("img2.jpg");
img3Url = getClass().getResource("img3.jpg");
img4Url = getClass().getResource("img4.jpg");
img5Url = getClass().getResource("img5.jpg");
img6Url = getClass().getResource("img6.jpg");
img1 = new JLabel(new
ImageIcon(Toolkit.getDefaultToolkit().createImage(img1Url)));
img2 = new JLabel(new
ImageIcon(Toolkit.getDefaultToolkit().createImage(img2Url)));
img3 = new JLabel(new
ImageIcon(Toolkit.getDefaultToolkit().createImage(img3Url)));
img4 = new JLabel(new
ImageIcon(Toolkit.getDefaultToolkit().createImage(img4Url)));
img5 = new JLabel(new
ImageIcon(Toolkit.getDefaultToolkit().createImage(img5Url)));
img6 = new JLabel(new
ImageIcon(Toolkit.getDefaultToolkit().createImage(img6Url)));
After that, I add all JLabels to JPanel and do setVisible() on each
JLabel using JButtons.
But when I create 6 JLables at one time, the memory usage increase up
to 22MB(!!!). If I wanted to use 20 images, the out of memory error is
sure.
So how should I build such application? What should I do to load into
memory only one image, which is currently displayed?
Please, help me.
Joshua Cranmer - 06 Mar 2007 22:17 GMT
> Hi,
>
[quoted text clipped - 38 lines]
>
> Please, help me.
Don't load the images until you need them, e.g.:
JLabel image;
public void showImage(URL url) {
image = new JLabel(new
ImageIcon(Toolkit.getDefaultToolkit().createImage(url)));
}
The garbage collector will free up the unused images in the meantime.
(If you want to be doubly sure, call Runtime.gc())
Daniel Pitts - 07 Mar 2007 06:07 GMT
On Mar 6, 1:11 pm, k.muc...@chello.pl wrote:
> Hi,
>
[quoted text clipped - 38 lines]
>
> Please, help me.
The 22MB might not be the actual active memory. Don't assume you are
going to run out of memory unless you actually do.
Instead of just guessing that an "out of memory error is sure [sic]",
try it with 20 images and see how much your memory increases.
In any case, if you are only displaying one image at a time, it
wouldn't hurt to only load one image at a time.
BTW, your example would be better written:
JLabel[] labels = new JLabel[6];
for (int i = 0; i < 6; ++i) {
String fileName = "img" + i + ".jpg";
URL url = getClass().getResource(fileName);
labels[i] = new JLabel(new ImageIcon(url));
}