Way2Java

Convert Application to Applet

BHAVANA

After observing the procedure of converting applet to application, now let us visualize the application to applet . Once you know how to convert applet to application, now you can guess the steps for application to applet.
Following is the application on Application to Applet that changes the background of the frame as per the button clicked.
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 is the applet obtained after converting application to applet.

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  

HTML code to run the above applet.



Changes to be made to Application to Applet conversion

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

Follow the steps of Application to Applet to land safely.