Images not working

I am not sure why but this code, took directally from this site, dosn't seem to be working. The JFame pops up but the picture dosn't show up even if I resize the frame.

import java.awt.*;

import java.awt.event.*;

import java.awt.image.*;

import java.io.*;

import javax.imageio.*;

import javax.swing.*;

/**

* This class demonstrates how to load an Image from an external file

*/

public class LoadImageApp extends Component {

BufferedImage img;

public void paint(Graphics g) {

g.drawImage(img, 0, 0, null);

}

public LoadImageApp() {

try {

img = ImageIO.read(new File("2c.gif"));

} catch (IOException e) {

}

}

public Dimension getPreferredSize() {

if (img == null) {

return new Dimension(100,100);

} else {

return new Dimension(img.getWidth(null), img.getHeight(null));

}

}

public static void main(String[] args) {

JFrame f = new JFrame("Load Image Sample");

f.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

f.add(new LoadImageApp());

f.pack();

f.setVisible(true);

}

}

Thanks

Message was edited by:

cyberjip

[1326 byte] By [cyberjipa] at [2007-11-26 20:18:11]
# 1

This should be a good lesson in why just having code to do the job is not enough, you must also understand how it works. First and foremost, you're loading an image called "2c.gif". Does this image even exist? Is it being found? Is it found but not able to be decoded? You don't know because you're swallowing the exception so change this:

try {

img = ImageIO.read(new File("2c.gif"));

} catch (IOException e) {

}

to this:

try {

img = ImageIO.read(new File("2c.gif"));

} catch (IOException e) {

e.printStackTrace();

}

Now run your program and monitor the output.

kablaira at 2007-7-10 0:41:37 > top of Java-index,Java Essentials,Java Programming...