简体   繁体   English

java.lang.NullPointerException错误

[英]java.lang.NullPointerException error

I am having trouble with this code: 我在使用此代码时遇到问题:

package shapes;

import java.awt.Graphics2D;
import javax.swing.JFrame;

public class Shapes extends JFrame {

public static void main(String[] args) {
    doDrawing();
}

private static void doDrawing() {
    Graphics2D g = null;
    // TODO Auto-generated method stub
    Graphics2D g2d = (Graphics2D) g;
     g2d.drawLine(20, 20, 100, 100);
}

}

But when i run it i get: 但当我运行它时,我得到:

Exception in thread "main" java.lang.NullPointerException
at shapes.Shapes.doDrawing(Shapes.java:17)
at shapes.Shapes.main(Shapes.java:10)

How shall i fix this problem? 我该如何解决这个问题?

You set g to null : 您将g设置为null

Graphics2D g = null;

and then cast this null and assign to g2d 然后转换此null并分配给g2d

Graphics2D g2d = (Graphics2D) g;

and then call a method of a null object instance. 然后调用null对象实例的方法。

You're trying to access a null element: 您正在尝试访问null元素:

Graphics2D g = null;

And then you're trying to do something like this: 然后你试图做这样的事情:

Graphics2D g2d = (Graphics2D) null;

That's why you're getting NullPointerException . 这就是你得到NullPointerException的原因。

I'm not really into Graphics class, but, based on this example from docs, I made this code 我不是真正进入Graphics类,但是,基于这个来自docs的例子 ,我制作了这段代码

import java.awt.*;
import java.applet.Applet;
import java.awt.geom.Rectangle2D;
import javax.swing.*;

public class Shapes extends JApplet {
    public static void main(String[] args) {
        JApplet app = new Shapes();
        JFrame f = new JFrame("Example");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.init();
        app.start();
        f.add("Center", app);
        f.pack();
        f.setVisible(true);
    }

    Shapes() {
    }

    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawLine(20, 20, 100, 100);
    }
}

It draws the line you provided on your code. 它绘制了您在代码中提供的行。

I hope it helps 我希望它有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM