Java getGraphics()方法的空指针异常

[复制链接]
查看11 | 回复1 | 2010-9-3 12:51:33 | 显示全部楼层 |阅读模式
想在JPanel里面画条线,但是一直报告空指针异常,请问这是什么原因呢?
import java.awt.*;
import javax.swing.*;
public class MyGame {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

new Myframe("Hello").lanch();
}
}
class Myframe extends JFrame
{
JPanel jp =null;

public Myframe(String s)
{

super(s);
}

public void lanch()
{

ImageIconim = new ImageIcon("E:/javadev/xuannan/Games/88.jpg");

JLabel lbl = new JLabel(im);

setBounds(300,65,700,550);

jp = new JPanel(null);

jp.setBounds(175,125,350,300);

jp.setBackground(Color.WHITE);

add(jp);



panelDrawLine();

add(lbl);

setVisible(true);
}

public void panelDrawLine()
{

jp.setVisible(true);

Graphics g=jp.getGraphics();


g.drawLine(175, 125, 525, 125); //就是这里报告空指针异常。
}
本人菜鸟,请说得通俗易懂点,谢谢~

}

回复

使用道具 举报

千问 | 2010-9-3 12:51:33 | 显示全部楼层
先来看一下官方文档关于getGraphics方法的说明:public Graphics getGraphics()Creates a graphics context for this component. This method will return null if this component is currently not displayable. Overrides:getGraphics in class ComponentReturns:a graphics context for this component, or null if it has none注意最后一句,返回值有可能是nulljp
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行