请问我这样引用画笔对吗?在线等
public class GraphicsCeshi extends JFrame {
public GraphicsCeshi(){
this.setBounds(20, 20, 800, 800);
this.setVisible(true);
Graphics g = null;
this.paint(g);
}
public void paint(Graphics g){
g.drawLine(200, 300, 200, 200); //画一条线
g.drawRect(100, 100, 200,200); //画一个矩形
g.drawOval(100, 100, 50, 50); //画一个圆
Font f=new Font("楷体",Font.BOLD,100); //设置字体
g.setFont(f);
g.drawString("我是XXX", 200,200); //写一个字符串
Color c=g.getColor(); //保存最初的颜色
g.setColor(Color.blue);//将笔的颜色改为蓝色
g.fillOval(300,300, 100, 80);//实心圆
g.setColor(c);//重新用回原来的颜色
}
public static void main(String[] args){
new GraphicsCeshi();
}
}
虽然可以运行,但是抛出异常:
Exception in thread "main" java.lang.NullPointerException
at Swingceshi.GraphicsCeshi.paint(GraphicsCeshi.java:24)
at Swingceshi.GraphicsCeshi.<init>(GraphicsCeshi.java:20)
at Swingceshi.GraphicsCeshi.main(GraphicsCeshi.java:39)
请问在swing中我该如何引用Graphics才算规范呢?
求改进!!! Java?swing?
[解决办法]
Graphics g = null;
this.paint(g);
不是没赋值,而是直接赋值成null了