A nice little star field
I initally wrote a star field program around 5 years ago in c++ and after I learned a bit of java I thought of re-writting it in java.
It's starts the animation as soon as its clicked and stops when it loses focus.
Can anyone tell me if this can be fine tuned to work better?
Initially I kept getting IllegalMonitorStateException and so I decided to make every method synchronized. ;)
Could someone explain why the applet works when the run() method has all its statements in a synchronized block?
There's only one thread in this program, so shouldnt it work properly without the synchronized keyword?
Ok here's the code.....
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*
<applet code=Stars.class width=300 height=100>
</applet>
*/
publicclass Starsextends Appletimplements Runnable,FocusListener
{
int index=0;
finalint STARS=300;
finalint WIDTH=300;
finalint HEIGHT=100;
int x[]=newint[STARS];
int y[]=newint [STARS];
boolean runOnce=true;//Added this flag so make sure that the star co-ordinates are generated only once.
boolean focussed=false;//Added this flag to suspend the thread.
Thread t;
publicvoid init()
{
index=0;
setBackground(Color.black);
setForeground(Color.white);
if(runOnce)
{
for(int i=0;i<STARS;i++)
{
x[i]=(int)(Math.random()*WIDTH);
y[i]=(int)(Math.random()*HEIGHT);
}
}
runOnce=false;
addFocusListener(this);
}
synchronizedpublicvoid start()
{
if(t==null ||!t.isAlive())
{
t=new Thread(this,"Stars_in_sky");
t.start();
}
}
synchronizedpublicvoid stop()
{
focussed=false;
notify();
}
publicvoid destroy()
{
t=null;
}
synchronizedpublicvoid focusGained(FocusEvent fe)
{
focussed=true;
notify();
}
synchronizedpublicvoid focusLost(FocusEvent fe)
{
focussed=false;
notify();
}
publicvoid run()
{
while(true)
{
synchronized(this)
{
while(!focussed)
{
try
{
wait();
}catch(InterruptedException e){}
}
if(index==WIDTH)index=0;
index++;
repaint();
try
{
t.sleep(50);
}catch(InterruptedException e){}
}
}
}
publicvoid paint(Graphics g)
{
for(int i=0;i<STARS;i++)
{
int xx=x[i]-index;
if(xx>0)//this check is written so that the stars that leave the screen at the left shows up
g.drawString(".",xx,y[i]);//at the right corner and continues to move left and the whole process repeats.
else
g.drawString(".",xx+WIDTH,y[i]);
}
}
}
Message was edited by:
ArcherKing
Sorry had to add one more line

