Applet

Applets are a web-based Java programs. They are embedded inside an Internet page, dowloaded and run directly within the browser on the client machine.







 
However, applets do not have a main method as an entry point, but instead, have several methods to control specific aspects of applet execution (all of them are public and void). lassed.  To make some functuonality one ore more of these methods must be overrided.

init() Java Applets often override and implement their own init method. The init method provides a mechanism to initialize the Applet once, similar to a constructor in other Java classes. The init method is the first method that is called for Java Applets and initializes object or environmental variables.
start() The start method for Java Applets begins the execution of the Java Applet. The start method is typically ran after the initialization of the Applet through the init method. Typically, you do not want to perform intensive computation within the start method as this will cause the Java Applet to load slowly. 
paint(Graphics) The paint method deals with the display of graphics on the applet
stop() The stop method will suspend the execution of a Java Applet. However, the stop method does not simply run after a user is finished and has closed the Applet. The stop method is also used when a user transitions to another application or views another web page to free up system resources for other computer applications.
destroy() The destroy method is used at the end of an Applet's life cycle. This method is used at the end of the execution of a Java Applet to free up any resources that may still have been used by the Applet. However, you should take care when working with the destroy method as there is not a guarantee that this method will be called as the Applet may have been shutdown before the method was called.

To see the applet in action, you need an HTML file with the Applet tag as follows:

<applet code='classname'  width='pixels'  height='pixels'>

Listeners

The listeners are interfaces or classes with  methods which must be overriden to describe the reaction of the events produced in a user interface. A listener is  called when the user does something to the user interface that causes an event. Altho these events usually come from the user interface, they can have other sources (eg, a Timer).  They must be linked  with the  components .

Some examples:


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

public class Bt extends Applet {
     Button  b1 = new Button("Bt 1"),  b2 = new Button("Bt 2");
     TextField  t = new TextField(" initial text",20);
      public void init() {
          b1.addActionListener(new B1());
          b2.addActionListener(new B2());
          add(b1);
          add(b2);
          add(t);
     }
     class B1 implements ActionListener {
          public void actionPerformed(ActionEvent e) {
                  t.setText("Bt 1");
          }
     }
     class B2 implements ActionListener {
          public void actionPerformed(ActionEvent e) {
                   t.setText("Bt 2");
          }
     }
}


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

public class Bt1 extends Applet {
   Button  b1, b2;
   B1 bls1 = new B1();
   B2 bls2 = new B2();
   B11 bls11 = new B11();
   TextField  t = new TextField("Click Bt1 to hide Bt2",20);
   boolean showBt2=true;
   public void init() {
          b1 = new Button("Bt1");
          b2 = new Button("Bt2");
          b1.addActionListener(bls11);
          b2.addActionListener(bls2);
          b1.addActionListener(bls1);
          add(b1);
          add(b2);
          add(t);
  }

  class B1 implements ActionListener {
          public void actionPerformed(ActionEvent e) {
              if(showBt2){
                  t.setText("Click Bt1 to hide Bt2");
              }else{
                  t.setText("Click Bt1 to show Bt2");
              }               
          }
  }
  class B2 implements ActionListener {
          public void actionPerformed(ActionEvent e) {
                   t.setText("Bt2 is clicked ");
          }
  }
  class B11 implements ActionListener {
      public void actionPerformed(ActionEvent e) {
          if(showBt2){
              remove(b2);               showBt2=false;
          }
          else {
              add(b2);               showBt2=true;
          }
      }
  }
}







The Listener for the Window
pAwt006
import java.awt.*;
import java.awt.event.*;
public class Ex {
public static void main(String [] args) {
Frame f = new Frame("Frame 1");
Menu m = new Menu("Menu 1");
m.add("Option 1");
m.add("Option 2");
MenuBar mb = new MenuBar();
mb.add(m);
f.setSize(300, 250);
f.setMenuBar(mb);
f.addWindowListener(new WL());
f.setVisible(true);
}
 static class WL extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
 }
}

Applet and application at the same time

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

import javax.swing.*;

public class Bt extends Applet {
    Button b1 = new Button("Bt 1"),b2 = new Button("Bt 2");
    TextField t = new TextField(" initial text",20);
    public void init() {
        b1.addActionListener(new B1());
        b2.addActionListener(new B2());
        add(b1);
        add(b2);
        add(t);
    }
    class B1 implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            t.setText("Bt 1");
        }
    }
    class B2 implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            t.setText("Bt 2");
        }
    }

    public static void main(String[] args) {     // A main() for the application:
        Bt applet = new Bt();
        JFrame aFrame = new JFrame("Bt");
        aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        aFrame.add(applet);
        aFrame.setSize(300,200);
        applet.init();
        applet.start();
        aFrame.setVisible(true);
    }
}

Example Frame, Menu
pAwt008
import java.awt.*;
import java.awt.event.*;
public class Ex {
    static int w=300,h=250;
    static Frame f;
 public static void main(String [] args) {
   f = new Frame("Frame 1");
   Menu m = new Menu("Menu 1");
   Button b = new Button("inc 10%"),
          b2 =  new Button("dec 10%");
   MenuItem mi1 = new MenuItem("Increment 10%");
   MenuItem mi2 = new MenuItem("Decrement 10%"); 
   m.add(mi1);
   m.add(mi2);
   mi1.addActionListener(new Inc());
   mi2.addActionListener(new Dec());
   MenuBar mb = new MenuBar();
   mb.add(m);
   f.setLayout(new FlowLayout());
   f.add(b);
   f.add(b2);
   b.addActionListener(new Inc());
   b2.addActionListener(new Dec());
   f.setSize(w, h);
   f.setMenuBar(mb);
   f.addWindowListener(new WL());
   f.setVisible(true);
 }
 static class WL extends WindowAdapter {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
 }
 static class Inc implements ActionListener{
     public void actionPerformed(ActionEvent e) {
         w+=w/10;
         h+=h/10;
         f.setSize(w, h); 
     }
 }
 static class Dec implements ActionListener{
     public void actionPerformed(ActionEvent e) {
         w-=w/10;
         h-=h/10;
         f.setSize(w, h);   
     }
 }
}

Canvas

Java allows creation and modification of images using both awt (Canvas) and the newer JFC 2D (JPanel and JFrame) architecture.

A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.  Java applets tie the canvas to the window frame. Output to the canvas takes place through a graphics context encapsulated by the Graphics class. An application must subclass the Canvas class in order to get useful functionality such as creating a custom component.  The paint method must be overridden in order to perform custom graphics on the canvas. 

The canvas origin (0,0) is set at the upper left corner position of its container. The graphics context is passed when the paint() or update() method is called. Use either setSize(x,y) or setBounds(x,y,w,h) to set the canvas dimensions.


Some  methods:

Shape awt JFC 2D
  • Line
  • Rectangle
  • (rounded)
  • Ellipse
  • Arc
  • Polygon
  • drawLine(x1,y1,x2,y2)
  • drawRect(x1,y1,x2,y2)
  • drawRoundRect(x1,y1,x2,y2,r1,r2)
  • drawOval(x,y,w,h)
  • drawArc(x,y,w,h,sdeg,ndeg)
  • drawPolygon(x[],y[],numPoints)
  • Line2D.Float(x1,y1,x2,y2)
  • Rectangle2D.Float(x1,y1,x2,y2)
  • RoundedRectangle2D.Float(x1,y1,x2,y2)
  • Ellipse2D.Float(x,y,w,h)
  • Arc2D.Float(x,y,w,h,sdeg,ndeg,clos)
  •  

The method drawString() is used to write simple text to the canvas.

Colors can be selected from the awt Color class constants: black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, yellow, BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW.
Note: The names do not match the basic sixteen colors system.

Custom colors with transparency can be created using the constructor Color(red, green, blue, [alpha]) where the parameters are integer [0 - 255] or float [0.0 - 1.0]. An alpha of 255 or 1.0 yields opaque [default]. For example: skyblue is 135,206,235 (ie. 87CEEB hText colors are set with either the setColor(color_obj) or the setForeGround(color_obj) method depending on the object. Background colors are set with setBackground(color_obj).

Object colors can be read using the integer methods: getRGB(), getRed(), getGreen(), getBlue() and getAlpha().

Font settings use awt Font class objects.

Font bigFont=new Font("TimesRoman",Font.ITALIC,24);

Note that the parameters are family, style (as a Font class constant) and point size. Style is one of PLAIN, ITALIC or BOLD.ex).

pAwt009                                                                                pAwt010
Applet application
import java.awt.*;
import java.applet.*;
public class Ex extends Applet {
    public void init(){
        setSize(250,350);
        setBackground(Color.yellow);
        setForeground(Color.BLUE);
        setFont(new Font("TimesRoman",Font.ITALIC,24));
    }
    public void paint (Graphics g){      
        g.drawString("This a String", 20, 20) ;
        g.fillRoundRect(50, 70, 95, 170, 45, 45);
               //  x,y,width, height,arcWidth,arcHeight
    }
}
import java.awt.*;
import java.awt.event.*;
public class Ex1 {
    public static void main (String[] arg){
        Frame f = new Frame("Ex 1");
        MyCanvas  cs = new MyCanvas();
        f.add("Center",cs);
        f.setSize(250,350);
        cs.setBackground(Color.yellow);
        cs.setForeground(Color.BLUE);
        cs.setFont(new Font("TimesRoman",Font.ITALIC,24));
        cs.repaint();
        f.setVisible(true);
        f.addWindowListener(new WL());
    }
     static class WL extends WindowAdapter {
         public void windowClosing(WindowEvent e) {
              System.exit(0);
         }
     }
}
class MyCanvas extends Canvas{
    public void paint (Graphics g){      
         g.drawString("This a String", 20, 20) ;
         g.fillRoundRect(50, 70, 95, 170, 45, 45);
    }
}


Layouts

BorderLayout
 
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Border extends Applet {
    public void init(){
        setLayout(new BorderLayout());
        add("North", new Button("North"));
        add("South",new Button("South"));
        add("East",new Button("East"));
        add("West",new Button("West"));
        add("Center",new Button("Center"));
   }
}
import java.awt.*;
import javax.swing.* ;
public class Ex1 {
    public static void main (String[] arg){
        JFrame f = new JFrame("Frame 1");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new BorderLayout());
        f.add("North", new Button("North"));
        f.add("South",new Button("South"));
        f.add("East",new Button("East"));
        f.add("West",new Button("West"));
        f.add("Center",new Button("Center"));
        f.setSize(450, 250);
        f.setVisible(true);
    }
}


FlowLayout

FlowLayout() 
FlowLayout(int align) – FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER;
FlowLayout(int align, int hgaps, int vgaps);

 
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Flow extends Applet {
   public void init(){
       setLayout(new FlowLayout());
       String flowButtons[] = {"One","Two","Three","Four","Five"};
       for(int i=0;i<flowButtons.length;++i)
            add(new Button(flowButtons[i]));
    }
}
import java.awt.*;
import javax.swing.* ;
public class Ex1 {
    public static void main (String[] arg){
        JFrame f = new JFrame("Frame 1");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new FlowLayout());
        String flowButtons[] =
{"One","Two","Three","Four","Five"};
        for(int i=0;i<flowButtons.length;++i)
             f.add(new Button(flowButtons[i]));   
        f.setSize(450, 250);
        f.setVisible(true);
    }
}



GridLayout

GridLayout(int rows, int cols)
GridLayout(int rows, int cols, int hgaps, int vgaps)

 
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Grid extends Applet {
    public void init(){
         setLayout(new GridLayout(2,3));
         String gridButtons[] = {"(0,0)","(1,0)","(2,0)","(0,1)","(1,1)","(2,1)"};
         for(int i=0;i<gridButtons.length;++i)
              add(new Button(gridButtons[i]));
     }
}



GridBagLayout

 
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class GridBag extends Applet {
    GridBagLayout gridBagLayout = new GridBagLayout();
     public void init(){
         setLayout(gridBagLayout);
         Button gridBagButtons[] = new Button[9];
         for(int i=0;i<9;++i) gridBagButtons[i] = new Button("Button"+i);
         int gridx[] = {0,1,2,0,2,0,1,1,0};
         int gridy[] = {0,0,0,1,1,2,2,3,4};
         int gridwidth[] = {1,1,1,2,1,1,1,2,3};
         int gridheight[] = {1,1,1,1,2,2,1,1,1};
        GridBagConstraints gridBagConstraints[] = new GridBagConstraints[9];
        for(int i=0;i<9;++i) {
             gridBagConstraints[i] = new GridBagConstraints();
             gridBagConstraints[i].fill=GridBagConstraints.BOTH;
             gridBagConstraints[i].gridx=gridx[i];
             gridBagConstraints[i].gridy=gridy[i];
             gridBagConstraints[i].gridwidth=gridwidth[i];
             gridBagConstraints[i].gridheight=gridheight[i];
             gridBagLayout.setConstraints(gridBagButtons[i],gridBagConstraints[i]);
             add(gridBagButtons[i]);
         }
    }
}


Null Layout

 
import java.applet.*;
 import java.awt.*;
 public class abs_val extends Applet {
     Button buttonv = new Button("vert");
     Button button = new Button("Button at (10,80)");
     public void init() {
         setLayout(null);
         buttonv.setBounds(115,10,35,100);
         button.setBounds(10,80,100,30);
         add(buttonv);
         add(button);
     }
 }
import java.awt.*;
import javax.swing.* ;
public class Ex1 {
    public static void main (String[] arg){
        JFrame f = new JFrame("Frame 1");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Button buttonv = new Button("vert");
        Button button = new Button("Button at (10,80)");
        f.setLayout(null);
        buttonv.setBounds(115,10,35,100);
        button.setBounds(10,80,100,30);
        f.add(buttonv);
        f.add(button);    
        f.setSize(450, 250);
        f.setVisible(true);
    }
}