Java的getGraphics()返回空指针问题

敲打Java书上操作线程自动画线段(线程的休眠里面的实例)的代码时,编译时

Graphics graphics=getGraphics()

graphics.setColor(getC());

产生空指针异常。

网上有人说组件的图形上下文,如果其没有,则返回 null,所以我们的图形界面没有显示出来之前getGraphics()返回都是null

再看这个程序:继承了JFrame的类是先初始化构造函数(构造函数里面有Graphics graphics=getGraphics()),之后再调用init()函数实现设置setVisible(true);因而getGraphics()返回都是null。

怎么解决呢,再网上找了好久没找到。

既然这个没法把setvisible(true)放在Graphics graphics=getGraphics()前,那么我可以等到你setvisible(true)之后graphics不为空的时候再进行操作呀,所以我加了个if语句:

Graphics graphics=getGraphics();
if(graphics!=null) {
    graphics.setColor(getC());
    graphics.drawLine(x, y, 100, y++);
    if(y>=80) {
    	y=50;
    }
}
问题解决!

猜你喜欢

转载自blog.csdn.net/Mountain_Zhou_only/article/details/79944009