我打算用做一个类似桌面既屏保,很简单的,就是有一个球,碰壁后反弹,不过编程的时候出了问题,
Exception in thread "main" java.lang.NullPointerException
代码如下:
import java.awt.*;
import javax.swing.*;
public class animation extends JFrame implements Runnable
{
Graphics gr;
Image i;
int x=0,y=0,a,b,w,h;
public animation()
{
w=Toolkit.getDefaultToolkit() .getScreenSize().width;
h=Toolkit.getDefaultToolkit() .getScreenSize().height;
i=createImage(w,h) ;
//System.out.println("HI");
gr=i.getGraphics() ; //就是这里出问题, i.getGraphics()这个方法返回一个Graphics类,我觉得
//可能不能实例化这个Graphics类了,
GraphicsDevice gra=GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
gra.setFullScreenWindow(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void run()
{
while(true)
{
x=x+a;
y=y+b;
if(x>w)
{
a=-1;
}else if(x<0)
{
a=1;
}else if(y>h)
{
b=-1;
}else if(y<0)
{
b=-1;
}
try{
Thread.sleep(100);
}catch(Exception e)
{}
repaint();
System.out.println("hello");
}
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
gr.setColor(Color.black);
gr.drawRect(0,0,w,h);
gr.setColor(Color.BLUE);
gr.drawOval(x,y,w,h);
g.drawImage(i,w,h,this);
}
public static void main(String[] args) {
new Thread(new animation()).start();
}
}
关于双缓冲问题