Way2Java

Banner Applet cum Application

Example on Moving Banner and Applet cum Application that works applet as an application also

Banner is a string that moves either horizontally or vertically across the applet window. In the following program, the string "S N Rao" is moved horizontally. This is done both as applet and application ( Applet cum Application ).

Before going with this program, go through the multithreading topic as some concepts are required here. sleep() method of Thread class makes a running thread to become inactive for the specified time passed, as parameter, in milliseconds. Here, for every iteration, the thread becomes inactive for 110 milliseconds. To get the size of the applet window, we used getSize().width and getSize().height methods. clearRect() method of Graphics class clears the earlier image existing on the applet window. For every 110 milliseconds the old image is removed and the new one is drawn (or to say, old image is overridden with new one); this is how animation is implemented.

import java.awt.*;
import java.applet.*;
public class Move extends Applet implements Runnable
{
    String str = "Wishes from way2java.com";
    Thread t1 = null;
     public void init() 
     {
        t1 = new Thread(this);
        t1.start();
     }
     public void run () 
     {
         char ch1;
         while(true)                     // no condition checking
         {
             try 
             {
                repaint();               // it calls paint() implicitly
                Thread.sleep(110);  //  interval of 110 milliseconds
                ch1 = str.charAt(0);
                str = str.substring(1, str.length());
                str += ch1;
             } 
             catch(InterruptedException e) {}
        }
    }
    public void paint(Graphics g) 
    {
        g.drawString(str, 40, 100);
        showStatus("I am a banner programmer.");// display on status bar
    }
}

File Name: GoAhead.html

	


Screenshot of MovingBanner.html

ch1 = str.charAt(0);
str = str.substring(1, str.length());

charAt() method of String class returns the character available at the index position passed as parameter. With every iteration, the character changes as index number changes. The String class substring() method returns few characters of a string available in between the integer values passed as parameter.

Now Converting Application to Applet ( of Applet cum Application )

An application can be converted to an applet or vice versa. It is required to import two packages java.applet and java.awt for Applet and Graphics classes and if required, for event handling, java.awt.event package also.

Following are the simple steps to remember while migrating from an application to applet.

  1. Import java.applet and java.awt packages.
  2. Include init() method in place of constructor
  3. No main() method
  4. Write paint() method to draw something on the applet window
  5. Create one HTML file to give the address of applet and window size


Applet cum Application

A program that works both as an applet and application can be developed. It is only a programming technique, generally not used in programming, but increases the logic of coding. We write both init() method understood by the browser and main() method understood by the JRE. As usual, write HTML file, with <applet> tag to run in browser; when run in the browser init() method is called but main() is not called. When the Java file is opened at the command prompt, it calls main() method but not init() method. From the main() method, we call init() explicitly as actual code exists in init() method. In anyway, the code of init() method is executed.

By coding it is not important but by logic-wise, it is. Three buttons are crated and when clicked, the background of the window changes.

Note: This program requires the knowledge of AWT components and event handling. Better understand this program after completing AWT topics.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ApplicationApplet extends Applet implements ActionListener
{	
    Button ob, yb, mb;
    public void init()
    {
        setLayout(new FlowLayout());
        add(ob = new Button("Orange"));
        add(yb = new Button("Yellow"));
        add(mb = new Button("Magenta"));
        ob.addActionListener(this);
        yb.addActionListener(this);
        mb.addActionListener(this);
     }
     public void actionPerformed(ActionEvent e)
     {
         String label = e.getActionCommand();
         if(label.equals("Orange")) 	setBackground(Color.orange);
         else if(label.equals("Yellow")) 	setBackground(Color.yellow);
         else if(label.equals("Magenta")) 	setBackground(Color.magenta);
     }
     public static void main(String args[] )
     {
         Frame f1 = new Frame();  // to get a Frame object to exe
         ApplicationApplet app = new ApplicationApplet(); 
         app.init();
         f1.add(app, "Center"); // to work with application
         f1.setTitle("Application cum Applet");
         f1.setSize(300,250);
         f1.setVisible(true);
     }
}

HTML file, File Name: AA.html


Frame f1 = new Frame();

To work as a frame, a Frame object is created.

f1.add(app, “Center”);

For the frame object, the applet is added at the center.

ApplicationApplet app = new ApplicationApplet();
app.init();

To call the init() method, an object of ApplicationApplet, app is created and init() is called. We know, init() is called implicitly by the browser and not main(). So, when executed as an application, init() is required to call explicitly.


More attributes of <applet> tag

We know to run an applet, a HTML file is required. The applet is included in the HTML file with <applet> tag. When the user clicks over the hyperlink on a Web page, the server downloads the applet onto the client machine. The browser executes the applet. For this, the browser should come with JVM. Of course, now-a-days, majority of browsers come with JVM by default. The browsers with JVM are known as Java enabled browsers. Browser does not require a compiler as compiled applet file is given to browser to execute.

We used earlier, only code, width and height attributes of <applet> tag, but <applet> tag comes with many more attributes. Total attributes are summarized as here under.

Mandatory attributes

  1. code: Here, we write the name of the applet that should be loaded by the browser.
  2. width: This attribute gives the width of the applet window in pixels
  3. height: This attribute gives the height of the applet window in pixels

Optional attributes

  1. codebase: Generally, the html file and the applet file exist in the same folder or JAR file. If the applet file exist in a different folder, then the address of he applet is given with this attribute.
  2. alt: Stands for alternative text. If the browser is unable to display the applet for some reason, then the text of the alt is displayed.
  3. vspace: It gives the vertical space between the applet window and the surrounding the text in the browser.
  4. hspace: It gives the horizontal space between the applet window and the surrounding the text in the browser.

The <applet> tag may contain an optional following child tag.

<param name="firstNum" value="18">

The <param> takes a key/value pair. This tag data is used to initialize the applet with some default properties.

An <applet> tag with all the attributes looks as follows.

<applet
code="Move.class"
codebase="d:\jyostna"
vspace = "40"
hspace = "60"
alt = "Cyber Towers building not displayed" >

<param name="distance" value="20">
</applet>