Thursday, 6 September 2012

Java Animation


Introduction of Java Animation


Programm

Save MyWindowAdapter.java

import java.awt.event.*;
public class MyWindowAdapter extends WindowAdapter
{
	public void windowClosing(WindowEvent we)
	{
		System.exit(0);
	}
}


Save MyFrame.java 
 
import java.awt.*;
public class MyFrame extends Frame implements Runnable
{
	int x, y, oldX, oldY, width, height, xdir, ydir;
	Thread t;
	
	MyFrame()
	{
		super("Animation Demo");
		setSize(600,400);
		addWindowListener(new MyWindowAdapter());
		setResizable(false);
		setBackground(Color.GRAY);
		setVisible(true);
		
		t = new Thread(this);
		t.start();
	}
	
	private void drawBall()
	{
		Graphics g = getGraphics();
		g.setXORMode(getBackground());
		
		/*
		if (oldX != -1 && oldY != -1)
			g.drawOval(oldX, oldY, width, height);
		*/	
		g.setColor(Color.BLUE);
		g.drawOval(x, y, width, height);
	}
	
	public void run()
	{
		width = 30/2;
		height = 30/2;
		
		x = (getSize().width - width) / 2;
		y = (getSize().height - height) / 2;
		oldX = oldY = -1;
		
		Random r = new Random();
		
		if (r.nextInt(5) % 2 == 0)
			xdir = 1;
		else
			xdir = -1;
			
			
		if (r.nextInt(5) % 2 == 0)
			ydir = 1;
		else
			ydir = -1;
		
		boolean flag = true;
		
		while (flag)
		{
			drawBall();
			try
			{
				Thread.sleep(5);
			}
			catch (InterruptedException exp){}
			
			oldX = x;
			oldY = y;
			
			x = x + (1*xdir);
			y = y + (1*ydir);
			
			if (x <= 0 || x >= getSize().width - width)
				xdir *= -1;
			if (y <= 0 || y >= getSize().height - height)
				ydir *= -1;
		}
	}
}


Save GUI1.java

public class GUI1
{
	public static void main(String args[])
	{
		MyFrame mf = new MyFrame();
	}
}

No comments:

Post a Comment