Paid for writing

In case you like my writing and would like me to write for your website, then please leave a comment to any of my blog article, mentioning your Email Id and I will reply back. Thanks

Friday, April 24, 2009

Drawing Moving Banners in Java Applet

The following source code explains how to draw a simple moving banner in java applets

Lets check out the source code first.



//MovingBanners.java
import java.awt.*;
import java.applet.*;

/*
<applet code="MovingBanners" width=600 height=600>
*/


public class MovingBanners extends Applet implements Runnable
{
String msg="ANAND";
Thread t;
boolean stop;
int x1,x2,x3,y1,y2,y3,y4,x4;

public void init()
{
setForeground(Color.red);
x1=x2=x3=x4=y1=y2=y3=y4=300;
}

public void start()
{
t=new Thread(this);
stop=false;
t.start();
}

public void run()
{
while(x1<600)
{
try
{
repaint();
Thread.sleep(500);
x1+=10;
y2+=10;
x3+=10;
y3+=10;
x4-=10;
y4-=10;

}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}

public void stop()
{
t=null;
msg="";

}

public void paint(Graphics g)
{
g.drawString(msg,x1,y1);
g.drawString(msg,x2,y2);
g.drawString(msg,x3,y3);
g.drawString(msg,x4,y4);
}
}



Explanation

1. The class imports two java packages the applet.* and awt.*. This are required for the applet as a whole and the elements inside the applet.
2. Class MovingBanners extends the Applet class and implements the Runnable interface.
3. The Applet class is extended to override the functions init(), start(), stop(), destroy() and paint().
4. The moving banner will move the text "ANAND" inside the applet window.
5. The init() funtion will set the foreground color to red and will define the starting co-ordinates.
6. The start() function will will create a new Thread and will call the thread's start() function.
7. The thread's start() function will call the run() function which simply does the job of changing the co-ordinates and calling the repaint() function.
8. Although variables x1--x4 and y1--y4 are used. You will observe that variables y1 and x2 are not changing.
9. The thread will sleep for 500 milliseconds after it calls the repaint().
10. repaint() internally calls the paint() function. The paint function uses the drawString() function of Graphics class and draws the message on the screen.

0 comments: