2012년 5월 3일 목요일

Java 깜박거림 없는 애니메이션 예제


Java 깜박거림 없는 애니메이션 예제
더블버퍼링을 이용..

package kr.etri.softgear;


import java.awt.*;
import javax.swing.JFrame;


public class AniBall extends JFrame {


int x=150,y=100, xdir=1, ydir=2;
Image offScreenImage;
Graphics offScreen;
 
public AniBall()
{
setVisible(true);
setSize(300,200);

   offScreenImage = createImage(getSize().width, getSize().height);
   offScreen = offScreenImage.getGraphics();
}

public void paint(Graphics g)
{
offScreen.setColor(Color.white);               //background color
offScreen.clearRect(0,0,getWidth(),getHeight());//background
move();                       //updates the balls position
offScreen.setColor(Color.blue);        //draws a new ball
offScreen.fillRect(0,0,300,200);
offScreen.setColor(Color.red);        //draws a new ball
offScreen.fillOval(x,y,20,20);

g.drawImage(offScreenImage, 0, 0, this);
}

public void update(Graphics g)
{
   paint(g);
}

public void destory()
{
offScreen.dispose();
}

public void move()
{
if(x<0||x>getWidth())
xdir*=-1;
if(y<0||y>getHeight())
ydir*=-1;
x+=xdir;
y+=ydir;
}


/**
* @param args
*/
public static void main(String[] args) {
AniBall crg = new AniBall();

int step=0;
while(true)
{
crg.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) { 
//
}
}

}
}

댓글 없음:

댓글 쓰기