使用Graphics.drawImage时的java.lang.NullPonterException(image,x,y,ImageObserver)

时间:2013-06-16 01:47:08

标签: image nullpointerexception jpanel bufferedimage drawimage

我尝试在面板上使用ImageIcon绘图和图像方式,我尝试使用ImageIO.read绘图方式,我已经构建并重建了多个项目,每次出现错误时都会显示:

Exception in thread "main" java.lang.NullPointerException
    at Image_Test.screen.draw(screen.java:41)
    at Image_Test.Basic.run(Basic.java:23)
    at Image_Test.Basic.main(Basic.java:16)

screen.java:41是具有此确切代码的行:

g.drawImage(test, 100, 100, null);

我已经看过不同作者的4或5个教程,所有这些教程都使用null作为此方法中的最后一个参数。这是我的整个Basic类的副本(有主要方法),以及我的屏幕类(有drawImage方法)。这是项目中唯一的两个类。

package Image_Test;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;

public class Basic
{
    public JFrame window;
    public String title = "The Title for This Window";
    public screen screen = new screen();
    public Graphics g;

    public static void main(String[] args) { new Basic().run(); }

// The run() method is pretty much the main method
    public void run ()
    {
        buildWindow();
        screen.draw(g);
    }

    public void buildWindow ()
    {
        window = new JFrame(title);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        window.add(screen, BorderLayout.CENTER);

        window.setSize(1366, 768);

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        window.setLocation(dim.width/2-window.getSize().width/2, dim.height/2-window.getSize().height/2);

        window.setVisible(true);
    }   
}

package Full_Game_Test_02;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;

public class screen extends JPanel
{
    public Image Start_Idle;
    public Image Start_Active;
    public Image Exit_Idle;
    public Image Exit_Active;

    Image test = null;

    public screen ()
    {
        test = screen.loadImage("/Start_Active.png");
    }

    public void loadImages ()
    {
        Start_Active = new ImageIcon("C:\\Developing\\Start_Active").getImage();
        Exit_Idle = new ImageIcon("C:\\Developing\\End_Idle").getImage();
        Exit_Active = new ImageIcon("C:\\Developing\\End_Active").getImage();
    }

    public void draw (Graphics g)
    {
        g.drawImage(test, 100, 100, null);
    }

    public static Image loadImage (String file)
    {
        Image image = null;

// Exception 1      
        try
        {
            image = ImageIO.read(screen.class.getResource(file));
        }
        catch (Exception e1)
        {
            System.out.println("Exception 1");
        }

        return image;
    }
}

1 个答案:

答案 0 :(得分:0)

这一行:

    screen.draw(g);

不起作用(gnull并导致异常),而且不需要。您的成员变量g也不是。

如果您有一个JPanel(或子类,如Screen),它会在JFrame或类似的屏幕上显示,Swing会处理这幅画。