Tuesday, 6 March 2012

Random color balls(Multithreaded GUI)


CODING:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
class sample extends Canvas implements Runnable
{
Thread t;int i;
int a=50,b=250,interval=0;
Color color=Color.yellow;
public sample(int interval,Color color)
{
this.interval=interval;
this.color=color;
setSize(250,250);
setVisible(true);
t=new Thread(this);
t.start();
}
public void run()
{
while(true)
{
for(i=0;i<=40;i++)
{
try
{
t.sleep(interval);
}
catch(InterruptedException e)
{
}
b=b-5;a=a+2;
repaint();
}
for(i=0;i<=40;i++)
{
try
{
t.sleep(interval);
}
catch(InterruptedException e)
{
}
b=b+5;a=a+2;
repaint();
}
for(i=0;i<=80;i++)
{
try
{
t.sleep(interval);
}
catch(InterruptedException e)
{
}
a=a-2;
repaint();
}
}
}
public void paint(Graphics g)
{
int u,y,z;
Color c;
u=(int)(Math.random()*255);
z=(int)(Math.random()*255);
y=(int)(Math.random()*255);
c=new Color(u,y,z);
g.setColor(c);
g.fillOval(a,b,50,50);
}
}
class ThreadGUI extends Frame
{
ThreadGUI()
{
setSize(900,350);
setVisible(true);
Panel pan=new Panel();
pan.setLayout(new GridLayout(1,3));
sample sam1=new sample(5,Color.red);
sample sam2=new sample(6,Color.blue);
sample sam3=new sample(4,Color.green);
pan.add(sam1);
pan.add(sam2);
pan.add(sam3);
setLayout(new GridLayout(1,1));
add(pan);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent el)
{
System.exit(0);
}
}
);
}
public static void main(String args[])
{
new ThreadGUI();
}
}

Natural Scenery