线程“main”java.lang.NullPointerException中出现异常-java错误
当我运行代码时,出现以下错误: 线程主java.lang.NullPointerException中出现异常线程“main”java.lang.NullPointerException中出现异常-java错误,java,exception,user-interface,main,graphics2d,Java,Exception,User Interface,Main,Graphics2d,当我运行代码时,出现以下错误: 线程主java.lang.NullPointerException中出现异常 您没有为Graphics2D和g分配任何内容,因此NPE 请参阅AmitD的答案,以了解对该问题的更详细分析,并指出如何解决该问题。因为您尚未初始化图形2d g,所以g为空 NPE的真正原因是Graphics2D是一个抽象类,您不能实例化它 您可以创建Graphics2D实例的实例,如下所示 GraphicsEnvironment env = GraphicsEnviro
您没有为Graphics2D和g分配任何内容,因此NPE
请参阅AmitD的答案,以了解对该问题的更详细分析,并指出如何解决该问题。因为您尚未初始化图形2d g,所以g为空 NPE的真正原因是Graphics2D是一个抽象类,您不能实例化它 您可以创建Graphics2D实例的实例,如下所示
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
env.createGraphics(BufferedImage);
也可以使用BuffereImage中的createGraphics
如果未将值分配给已分配的对象,则其默认值为null。因此,当您引用g时,您没有引用任何内容。如果您在任何位置使用图形对象,而不是在paint*中或从那里调用的方法,那么很可能您做得不对。
Graphics2D g;
static JFrame jf = new JFrame();
Image Air;
Image Grass;
Image icon;
public Main() {
icon = new ImageIcon(this.getClass().getResource("Icon.png")).getImage();
Grass = new ImageIcon(this.getClass().getResource("Grass.png")).getImage();
Air = new ImageIcon(this.getClass().getResource("Air.png")).getImage();
jf.setIconImage(icon);
drawBlock(Air,0,0);
}
private void drawBlock(Image img, int x, int y) {
g.drawImage(img,x,y,null);
}
public static void main(String[] args) {
jf.setSize(792,528);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.setTitle("Minecraft 2D Adventure");
new Main();
}}
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
env.createGraphics(BufferedImage);
public Graphics2D createGraphics()