Convert Applet to Application

After knowing the differences between applets and applications and Applet cum Application, let us see how to convert an Applet to Application. For this, best one is a GUI applet.
Following program is an applet and later converted to an application. Then, steps of conversion of Applet to Application are listed.

Following applet changes the background of the window as per the button clicked.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonDemo extends Applet implements ActionListener
{
  Button rb, gb, bb;
  
  public void init()
  {
    setLayout(new FlowLayout());                       // for applet, FlowLayout is the default also
   
    rb = new Button("Red");          
    gb = new Button("Green");
    bb = new Button("Blue");

    rb.addActionListener(this);
    gb.addActionListener(this);
    bb.addActionListener(this);

    add(rb);  add(gb);  add(bb);                       // no set methods
  }
  public  void actionPerformed(ActionEvent e)
  {
    String str = e.getActionCommand();
    
    if(str.equals("Red"))
      setBackground(Color.red);    
    else if(str.equals("Green"))
      setBackground(Color.green);    
    else if(str.equals("Blue"))
      setBackground(Color.blue);    
  }
}                                                      // class closes, no main()

HTML file to execute the above applet



Now let us change the above Applet to Application .

Following is the application obtained after converting the Applet to Application.

import java.awt.*;
import java.awt.event.*;

public class ButtonDemo extends Frame implements ActionListener
{
  Button rb, gb, bb;
  
  public ButtonDemo()
  {
    setLayout(new FlowLayout());
   
    rb = new Button("Red");          
    gb = new Button("Green");
    bb = new Button("Blue");

    rb.addActionListener(this);
    gb.addActionListener(this);
    bb.addActionListener(this);

    add(rb);   add(gb);   add(bb);

    setTitle("This is Application");
    setSize(300, 300);
    setVisible(true);
  }
  public  void actionPerformed(ActionEvent e)
  {
    String str = e.getActionCommand();
    
    if(str.equals("Red"))
      setBackground(Color.red);    
    else if(str.equals("Green"))
      setBackground(Color.green);    
    else if(str.equals("Blue"))
       setBackground(Color.blue);    
  }
  public static void main(String args[])
  {
    new ButtonDemo();
  }
}                  

Following are the changes to be made from Applet to Application

1. Delete the statement "import java.applet" package
2. Replace extends Applet with Frame
3. Replace the init() method with constructor
4. Check the layout (for Applet, the default layout is FlowLayout and for Frame, it is BorderLayout)
5. Add setXXX() methods like setSize() etc.
6. Add the main() method
7. HTML is not required (delete it)

Leave a Comment

Your email address will not be published.