Saturday, October 23, 2010

How to make a java applet banner

As discussed Applet is small application accessed over internet.
Applet is a class in java,using extends keyword. (see how to extend Applet)
Applets can used to develop banner on your web page.
Lets see it with an example....
//Java Applet banner program
import java.awt.*;                                      //importing applet and awt package
import java.applet.*;
/*
<applet code="AppletBanner" width=300 height=50>
</applet>
*/
public class AppletBanner extends Applet implements Runnable{  //Multithreading is used
String msg="Simple Applet Banner";
boolean stopFlag;
Thread t=null;
//set colors N intialize thread
public void init(){
setBackground(Color.green);                                        //setting background and foreground color
setForeground(Color.red);
}
//Start thread this method is to start applet
public void start(){
t=new Thread(this);
stopFlag=false;
t.start();
}
//Thread runs
public void run(){
char ch;
//To display banner scrolling
for( ; ; ){
try{
repaint();
Thread.sleep(300);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
if(stopFlag)
break;
}
catch(InterruptedException e){
System.out.print(e);
}
}
}
//Applet stop ()
public void stop(){
stopFlag=true;
t=null;
}
//display banner
public void paint(Graphics g){
g.drawString(msg,50,30);
showStatus("Banner");
}
}


Now run the program as you do for a applet in applet viewer or browser.
expantion.(To See the basics of Applet)
   To display the banner scrolling repaint() is used to paint the banner again.
Threading concept is also used so handle the threads.
To display the banner scrolling  
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;

these are used. length() gives length of the string msg.
substring()
The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "from" and "to", not including "to" itselfsyntax
string.substring(from, to).

No comments:

Post a Comment