package chapter4;
import java.awt.Color;
import java.awt.Graphics;``
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.JFrame;
/**
*
* @author Ale
*/
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);
Toolkit tk= Toolkit.getDefaultToolkit();
image= tk.getImage(getURL("yoshi.PNG"));
}
private URL getURL(String filename){
URL url;
try{
url= this.getClass().getResource(filename);
}
catch(Exception e){}
return null;
}
/**
*
* @param g
*/
@Override
public void paint(Graphics g){
Graphics2D g2d=(Graphics2D) g;
g2d.setBackground(Color.WHITE);
g2d.fillRect(0, 0, getSize().width, getSize().height);
g2d.drawImage(image, 20, 40, this);
}
}
图像与此类位于同一文件夹中,但它给了我错误并且不显示图像。这些是错误:
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:115)
还有一些类似的。请需要帮助。该文件是来自 mario 的 yoshi 的 png 文件