开发者社区> 问答> 正文

main函数中出现空指针异常如何解决?

编译通过,但运行时出现空指针异常,可是找不到哪里出现了空指针。
代码如下:

public class MyDrawPanel extends JPanel
{

public void paintComponent(Graphics g)
{
    Graphics2D g2d=(Graphics2D) g;
    int red=(int)(Math.random()*255);
    int green=(int)(Math.random()*255);
    int blue=(int)(Math.random()*255);
    Color startColor=new Color(red,green,blue);
    
    int red2=(int)(Math.random()*255);
    int green2=(int)(Math.random()*255);
    int blue2=(int)(Math.random()*255);
    Color endColor=new Color(red2,green2,blue2);
    
    GradientPaint gradient=new    GradientPaint(70,70,startColor,150,150,endColor);
    g2d.setPaint(gradient);
    g2d.fillOval(70,70,100,100);
}
public static void main(String[] args)
{
    MyDrawPanel my=new MyDrawPanel();
    Graphics f=my.getGraphics();
    my.paintComponent(f);
}
}

运行结果如下:
screenshot
请问应该如何解决呢?

展开
收起
蛮大人123 2016-03-11 13:05:20 2701 0
3 条回答
写回答
取消 提交回答
  • 加try ... catch捕获异常。
    2019-07-17 18:58:58
    赞同 展开评论 打赏
  • 我说我不帅他们就打我,还说我虚伪

    MyDrawPanel是一个JPanel,它不能独立存在,必须添加到某个窗口(例如JFrame或JApplet)中之后它里面的某些状态才会被设置,其中就包括你这里使用的Graphics
    所以你要先创建一个窗口,然后添加进去,然后才能调用paintComponent

    2019-07-17 18:58:58
    赞同 展开评论 打赏
  • 有对应的行数,可以在IDE里面调试就能定位到具体原因

    2019-07-17 18:58:58
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
《0代码搭应用》 立即下载
不止代码 立即下载
低代码开发师(初级)实战教程 立即下载