我用双缓冲写了这个程序,内容很简单,就是有一个小球,碰到壁就反弹,问题是,运行起来好象并不畅顺,虽然并不会产生闪烁的感觉,
不知道是程序问题还是电脑问题,代码如下,
package new_test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class animation extends JFrame implements Runnable,KeyListener
{
Graphics gr;
Image i;
int x=0,y=0,a=1,b=1,w,h;
public animation()
{
h=Toolkit.getDefaultToolkit() .getScreenSize().height;
w=Toolkit.getDefaultToolkit() .getScreenSize().width;
this.setUndecorated(true);
GraphicsDevice gra=GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
gra.setFullScreenWindow(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addKeyListener(this);
this.setVisible(true);
}
public void keyPressed(KeyEvent e)
{
System.exit(0);
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
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(2);
}catch(Exception e)
{}
//System.out.print(x);
//System.out.println(" "+y);
repaint();
}
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
// super.paint(g);
i=createImage(w,h) ;
gr=i.getGraphics();
gr.setColor(Color.black);
gr.drawRect(0,0,w,h);
gr.setColor(Color.BLUE);
gr.fillOval(x,y,100,100);
// g.drawString("Hello",x,y);
g.drawImage(i,0,0,this);
//g.drawOval(x,y,10,10);
}
public static void main(String[] args) {
animation a= new animation();
new Thread(a).start();
}
}
还有,我有一个问题,就是,如果用多线程的话,好像上边那个程序,会搞到CPU的占用率很大,应该是程序本身设计问题吧,
大家请指点一下吗,谢谢了~