I am having trouble fetching an image to show up in my J Frame. I am sure I put the file in the right place and have typed the name correctly. this is the code
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.net.URL;
import javax.swing.JFrame;
public class DrawImage extends JFrame {
private Image image;
public static void main(String[] args){
new DrawImage();
}
public DrawImage(){
super("DrawImage");
setSize(600,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File appBase = new File("."); //current directory
String path = appBase.getAbsolutePath();
System.out.println(path);
Toolkit tk = Toolkit.getDefaultToolkit();
image= tk.getImage(getURL("Castle.jpg"));
}
private URL getURL(String filename){
URL url=null;
try{
url=this.getClass().getResource(filename);
//url=DrawImage.class.getResource(filename);
//url=C:\hw/myProg/Graphics2d/Castle.jpg;
}
catch(Exception e){
System.out.print("spleen:");
}
return url;
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getSize().width, getSize().height);
g2d.drawImage(image, 0, 40, this);
}
}
What I get is the JFrame with black but no image and this write out to the cousle.
C:\hw\myProg\Graphics2d\.
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(Unknown Source)
at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
naturally my image file is in C:\hw\myProg\Graphics2d\Castle.jpg So what am I doing wrong? EDIT: OK I figured it out you can test which folder your ide complies from from this handy piece of code. in eclipse it is in the bin folder.
URL test = DrawImage.class.getResource("/");
System.out.println(test);