Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: Munchor on May 23, 2011, 04:48:42 pm

Title: Java Accessing Image Problem
Post by: Munchor on May 23, 2011, 04:48:42 pm
Code: [Select]
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:

Code: [Select]
javax.imageio.IIOException: Can't read input file!
Why can't it get the file, it's in the same directory. Thanks :)
Title: Re: Java Accessing Image Problem
Post by: jnesselr on May 23, 2011, 09:19:53 pm
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.
Title: Re: Java Accessing Image Problem
Post by: Binder News on May 23, 2011, 09:30:20 pm
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
Code: [Select]
this.getClass().getResource("filename");
Title: Re: Java Accessing Image Problem
Post by: Munchor on May 24, 2011, 02:52:35 am
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 :)