程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 一個Java小球撞擊牆面的小程序

一個Java小球撞擊牆面的小程序

編輯:關於JAVA

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;

}

}

}

}

用這個雙緩沖區 就解決了

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved