2012-12-08 58 views
1

这样的IM导入图像作为背景,由于某种原因它给我的使用方法:不知道为什么图像不显示任何

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) 

有人能帮助我吗?

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 
public class PixelLegendsMain extends JFrame implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
    } 
    public static void main(String[ ] args)throws Exception{ 
    PixelLegendsMain plMain = new PixelLegendsMain(); 
    arenaBuild arena = new arenaBuild(); 
    plMain.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 


    plMain.add(arena); 
    plMain.setSize(600,460);; 
    plMain.setVisible(true); 
    plMain.setResizable(false); 
    plMain.setLocation(200, 200); 
    } 
} 

这是主类和这样的:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.awt.Font; 
import java.awt.Graphics; 
import java.net.URL; 
import java.io.*; 
import javax.swing.Timer; 

public class arenaBuild extends JPanel{ 
    String picPath = "pictures/"; 
    String[] fileName = {picPath+"stageBridge.png", picPath+"turret.png"}; 
    ClassLoader cl = arenaBuild.class.getClassLoader(); 
    URL imgURL[] = new URL[2]; 
    Toolkit tk = Toolkit.getDefaultToolkit(); 
    Image imgBG; 
    public arenaBuild()throws Exception{ 
    for (int x=0;x<2;x++){ 
     imgURL[x]= cl.getResource(picPath+fileName[x]); 
    } 
    imgBG = tk.createImage(imgURL[0]); 
    } 
    public void paintComponent(Graphics g){ 
    g.drawImage(imgBG,0,0,600,460,0,0,600,460, this); 
    } 
} 

Thjis就是即时调用在IM的图像的新本,所以我会很感激,如果有人可以解释为什么发生这种情况,并帮助。我修复它:D

+1

尝试使用“/图片/”而不是“图片/”。并调用super.paintComponent(g) - 它不会解决你的直接问题,但将解决你的约束与其他问题 – MadProgrammer

+0

看看这个例子。 http://ideone.com/DpZz12 –

回答

1

看来我unfortuantely没有看我自己的代码足够长的时间,看来我是调用picPath两次,而不是路径是

"pictures/stageBridge.png" 

的是

"pictures/pictures/stageBridge.png" 

对不起,时间的浪费,并感谢大家的回答

+0

您应该将您的答案标记为此问题的答案。 –

+0

@caccho,我会但我必须等2天,谢谢你的信息 – Exikle

0

尝试打印当前的工作目录,以检查您的图像路径是否正确。

这是这样做的一个简单的方法:

System.out.println(new File(".").getAbsolutePath()); 

也许问题在于图像pictures/tageBridge.pngpictures/turret.png不是该文件的正确路径。

希望它有帮助!

+0

OP的代码不会从文件系统加载图像.... –

1

最可能的解释是您的tk.createImage(imgURL[0])调用正在通过null URL。

这怎么会发生?那么ClassLoader.getResource(String)方法是specified作为返回null如果它找不到资源...所以看起来问题是,您正在使用第一个资源的错误路径。

您使用显示的路径是这样的:"pictures/pictures/stageBridge.png"

  • 这似乎不大可能,你真的把你的图片在一个名为"pictures/pictures"目录。

  • 由于要调用的方法的对象ClassLoader上(而不是Class对象),则使用的是名义上相对路径将被视为绝对路径;例如,你会得到“/图片/ ...”,而不是“/ PixelLegendsMain /图片/ ...”