這裏是主類不斷收到nullpointerException?我試圖打印出的圖像
public class Testing extends JFrame{
private static final long serialVersionUID = 1L;
public Testing(){
setContentPane(new Canvas());
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String[] args0){
new Testing();
}
}
,並在Canvas類,該方法的drawImage發生錯誤。我已經做了一個res文件夾,我把我的圖像,並將其用作源文件夾。
public class Canvas extends JPanel{
Graphics g;
Graphics2D g2 = (Graphics2D)g;
BufferedImage image;
private static final long serialVersionUID = 1L;
public Canvas(){
setPreferredSize(new Dimension(800,600));
loadImage("/space.png");
draw(g2);
}
public void draw(Graphics2D g2){
g2.drawImage(image, 0,0,this);
}
public void loadImage(String path){
try {
image = ImageIO.read(
getClass().getResourceAsStream(path)
);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("image loading error");
}
}
}
謝謝你的幫助。
和我運行程序時出現的錯誤。
Exception in thread "main" java.lang.NullPointerException
at Canvas.draw(Canvas.java:21)
at Canvas.<init>(Canvas.java:18)
at Testing.<init>(Testing.java:11)
at Testing.main(Testing.java:17)
請將完整的堆棧跟蹤添加到您的原始問題。還請標識**產生錯誤的確切代碼行**。 –
沒有堆棧跟蹤被打印出來。調試只是說theres一個nullpointerException drawImage() – Bango
你的'g'是'null'。 –