Banner Applet cum Application


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



Applet cum Application

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.

2 thoughts on “Banner Applet cum Application”

  1. Well, i created a banner and a choose menu and also radio buttons in one program but the banner and choose menu are overlapping each other… how do i change the position of the moving banner?

Leave a Comment

Your email address will not be published.