Like us on Facebook to get the latest links daily

Friday, March 1, 2013

Beginners guide in Java Applet / embedding a java applet in HTML page with example


Modern day programming uses java as an object oriented programming. Using applet we can use java program embedded to any web program. Applet also provides data security and data encryption. If you are learning your first applet program then this tutorial is best for you.

Step 1: Write a simple applet code in java.

It can be done in two ways:
  • Opening a Notepad file in java bin directory and writing source code in it and save it with .java extension. Click here to know how to write a java program.
  • It can also be done from console window I have used this path: c:\Programfiles\java\Jdk1.7.0_06\bin>edit filename.java
Java Applet Sample code: 


// Reference all the required Java Libraries from Applet and awt package
import java.applet.Applet;
import java.awt.*;

//The Applet code
 public class firstApplet extends Applet
 {
        public void paint(Graphics g)
        {
          // Draw a rectangle width=250 height=100
            g.drawRect(0,0,250,100);

          // Set the color to blue
            g.setColor(Color.blue);

          // Write the message to the webpage at coordinate 10,50
            g.drawString("Look at the Java Applet Page!",10,50);
        }
 }

Step 2: Compile the Java Source code 

To compile the java file write the following code to console/Command prompt c:\Programfiles\java\Jdk1.7.0_06\bin>javac firstApplet.java
After the compilation of the firstApplet.java a firstApplet.class file will be generated to your bin directory, i.e. a platform independent byte code you will get.

Step 3: Create a HTML page that references applet

Create a HTML page firstApplet.html in the bin directory that consists of the following code.

<html>
<head>
        <title>
                      My First Applet Programming.
        </title>
</head>
<body>
        <b>This is my first Java Applet Programming</b> <applet code="firstApplet.class" height="100" width="250"></applet>
</body>
</html>


Step 4: Displaying the Applet in HTML page


Displaying the Applet can be done in two ways.
  • Open the created (i.e. firstApplet.html) html page with the browser.
  • Opening from the command prompt(console) c:\Programfiles\java\Jdk1.7.0_06\bin>appletviewer firstApplet.html

Hope you have learned your first applet programming from this tutorial.
Subscribe my page for more tutorials. Join my pages on facebook, twitter, google+
If you have any query please write your queries in comment box.   


Get E-mail Subscription for Latest Updates


Don't forget to Click on activation link , sent to your E-mail ID

No comments:

Post a Comment

You might also like:

Related Posts Plugin for WordPress, Blogger...