Thursday 2 July 2015

Applets - Examples


Examples

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

public class HelloWorldApplet extends Applet
{
   public void paint (Graphics g)
   {
      g.drawString ("Hello World", 25, 50);
   }
}

The Component class provides 1 life cycle method of applet,

public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.


Who is responsible to manage the life cycle of an applet?
Java Plug-in software.

How to run an Applet?
There are two ways to run an applet

By html file.

By appletViewer tool (for testing purpose).

Example for running in browser,

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Graphics Demo,

import java.applet.Applet;
import java.awt.*;
 
public class GraphicsDemo extends Applet{
 
public void paint(Graphics g){
  g.setColor(Color.red);
  g.drawString("Welcome",50, 50);
  g.drawLine(20,30,20,300);
  g.drawRect(70,100,30,30);
  g.fillRect(170,100,30,30);
  g.drawOval(70,200,30,30);
 
  g.setColor(Color.pink);
  g.fillOval(170,200,30,30);
  g.drawArc(90,150,30,30,30,270);
  g.fillArc(270,150,30,30,0,180);
 
 }
}

Displaying image in applet,

import java.awt.*;
import java.applet.*;
   
public class DisplayImage extends Applet {
 
  Image picture;
 
  public void init() {
    picture = getImage(getDocumentBase(),"sonoo.jpg");
  }
   
  public void paint(Graphics g) {
    g.drawImage(picture, 30,30, this);
  }
     
  }




No comments:

Post a Comment