import Java.awt.*;
import Java.applet.*;
public class OnlyChangeUpdate extends Applet implements Runnable
{
int X,Y,moveX,moveY,width,height;
Thread newThread;
public void init()
{
X=0;
Y=0;
moveX=20;
moveY=20;
width=getSize().width;
height=getSize().height;
setBackground(Color.black);
}
public void start()
{
newThread=new Thread(this);
newThread.start();
}
public void stop()
{
newThread=null;
}
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillOval(X,Y,15,15);
}
public void update(Graphics g)
{
paint(g);
}
public void run()
{
while(newThread !=null)
{
repaint();
try
{
Thread.sleep(80);
}
catch(InterruptedException E){}
X=X+moveX;
Y=Y+moveY;
if(X >= (width - 15))
{
X=width-15;
moveX=-moveX;
}
if(X<=0)
{
X=0;
moveX=-moveX;
}
if(Y>=(height-15))
{
Y=height-15;
moveY=-moveY+5;
}
if(Y<=0)
{
Y=0;
moveY=-moveY+5;
}
}
}
}
關鍵是屏幕不能刷新,我已經認識到這點了
後面講到的雙緩沖區可以解決的
import Java.awt.*;
import Java.applet.*;
public class UseDoubleBuffering extends Applet implements Runnable
{
int X,Y,moveX,moveY,width,height;
Thread newThread;
Image OffScreen;
Graphics drawOffscreen;
public void init()
{
X=0;
Y=0;
moveX=2;
moveY=3;
width=getSize().width;
height=getSize().height;
OffScreen = createImage(width,height);
drawOffscreen = OffScreen.getGraphics();
}
public void start()
{
newThread=new Thread(this);
newThread.start();
}
public void stop()
{
newThread=null;
}
public void paint(Graphics g)
{
drawOffscreen.setColor(Color.black);
drawOffscreen.fillRect(0,0,width,height);
drawOffscreen.setColor(Color.white);
drawOffscreen.fillOval(X,Y,15,15);
g.drawImage(OffScreen,0,0,this);
}
public void update(Graphics g)
{
paint(g);
}
public void run()
{
while(newThread !=null)
{
repaint();
try
{
Thread.sleep(50);
}
catch(InterruptedException E){}
X=X+moveX;
Y=Y+moveY;
if(X >= (width - 15))
{
X=width-15;
moveX=-moveX;
}
if(X<=0)
{
X=0;
moveX=-moveX;
}
if(Y>=(height-15))
{
Y=height-15;
moveY=-moveY;
}
if(Y<=0)
{
Y=0;
moveY=-moveY;
}
}
}
}
用這個雙緩沖區 就解決了