Omnimaga
General Discussion => Technology and Development => Computer Programming => Topic started by: Munchor on May 23, 2011, 04:48:42 pm
-
import javax.swing.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class Squared {
public static void main (String[] args)
{
Squared mySquared = new Squared();
}
public Squared()
{
Draw();
}
public void Draw()
{
JFrame mainFrame = new JFrame("Squared");
mainFrame.setSize(480,320);
BufferedImage img = null;
try {
img = ImageIO.read(new File("block.png"));
} catch (IOException e) {
e.printStackTrace();
}
JLabel picLabel = new JLabel(new ImageIcon( img ));
mainFrame.add(picLabel);
mainFrame.setVisible(true);
}
}
I have file named "Squared.java" and an image called "block.png" in the same folder and in the same package (using Eclipse); I get this:
javax.imageio.IIOException: Can't read input file!
Why can't it get the file, it's in the same directory. Thanks :)
-
Is it in the same directory that you are searching in, though? There is a method to get the full path of a file object. Use that instead of trying to read the picture file, and it will tell you where it is looking for it.
-
You need to place the image files in the source root. So, if your source (relative to the Eclipse project) is src/mypackage/Squared/<files>, you need to put the image under the src folder. Then, in the code, use this to get the URL of the resource
this.getClass().getResource("filename");
-
file:/home/david/Documents/Java/Squared/bin/block.png
Thanks a lot Graphmastur and Binder News. I get now, the image has to be in the folder where the class file is, thanks :)