CKEditor – adding custom style sheet

Within the CKEditor editor you can add in custom style sheets to assist with styling of the content within the editor and here is how you do it

CKEDITOR.config.contentsCss = '/css/mycssfilename.css' ;

After you have created the instance of the CKEditor you just need to add in to the configuration the contents cascading style sheet file.

JQuery

JQuery is a library API within the javascript language, the API (Application Program Interface) is classes/functions that do all of the work for you and you can access them.

Both google and Microsoft host the JQuery API for you, and all you need to do is to load in the javascript from either or server hosted setup, for google it would be this to get version 1.4.2 of the JQuery language.

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.2");
</script>
 
-- or one line
 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

or with MS you can use

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>

once you have the JQuery API loaded you can then access the HTML document objects by using the $ symbol and act on any part of that document object that supports the functions that you want to do, e.g. a div tag would have different options for styling compared to a span tag.

The API library set is defined abit more in that link, but in whole it is a very effective and usable API library that just makes life more fun :).

For example the code below will output a mini function that will for “each” number in the first parameter (can be anything, object, letters etc) and do the function, will in this case will square the value, but the .each command is very powerful,

$.each([1,2,3], function()
{
	document.write(this * this);
});

the reason why it is very powerful is because if you want to select a group of items and then on each of them alter there elements, then you just need to use the JQuery selection process, like so

$("div").each

and this will alter all of the div’s on the web page accordlying. Shall do some more posts on JQuery API once I have a full set of examples to attached to the post.

Web page inputs and insert into database – Part 2

As from here, where I outlined the javascript, html part of the exercised here is the php and mysql parts of the problem.

Here is the table that I created within MySQL

CREATE TABLE `User` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `firstName` VARCHAR(50) DEFAULT NULL,
  `lastName` VARCHAR(50) DEFAULT NULL,
  `email` VARCHAR(50) DEFAULT NULL,
  `phoneNum` VARCHAR(20) DEFAULT NULL,
  `guid` VARCHAR(36) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

As from my other post about MySQL triggers, so to find out more information about why please check out that page, and here is the trigger that I created for the above table.

CREATE TRIGGER User_insert 
BEFORE INSERT ON USER 
FOR EACH ROW 
BEGIN 
        SET NEW.guid = uuid(); 
END

The reason why I created this for was because within the exercise they asked “would forward planning, i.e. adding a unique code to the user details that could be used to validate their email address”, which by using a uuid, you can use that as a unique code.

so the only part left is the PHP that will connect to the database and also sanitize the inputs within sql insert. So created a class that has a constructor that will open a database connection to a database

      private $dbLink;
      /* connect to the database*/
      function __construct($host = "localhost", $user = "user", $password = "password", $database = "database")
      {
	$this->dbLink = mysql_connect($host, $user, $password);
	if (!$this->dbLink) die("no database present");
	if (!mysql_select_db($database, $this->dbLink))
	  die("no database within the database");
      }

Here I try to sanitize the insert string so that it will use the mysql_real_escape_string, this will use a php function that helps with SQL injections, also I am using the stripslashes and then trim the string to make sure that there is no white spaces (or any valid text left).

      /* santize the input for a mysql database */
      public function santizeInput($theStr)
      {
	return trim(stripslashes(mysql_real_escape_string($theStr)));
      }

and then to insert the data, just use the mysql_query and the sanitize function above to insert data into the database.

      /* insert the data into the database */
      public function insertData($sqlData)
      {
	mysql_query($this->santizeInput($sqlData), $this->dbLink) or die("Error inserting data");
      }

And here is where I get the data from the form post from the web page and then double sanitize the data and then create a database link, which in-turn use to insert the data.

    // could use foreach loop $_POST inputs, but I personally prefer to pick them up.
    $firstname = $_POST['firstname'];
    $secondname =$_POST['secondname'];
    $email = $_POST['email'];
    $phonenumber = $_POST['phonenumber'];
 
    /* could do additional checks on input incase it is sent via backend POST and not via the webpage,  could do with regular expression as well ? */
    $db = new databaseAccess("localhost", "username", "password", "database");
    /* can santize the inputs to make sure that there is some data to "play" with */
    $firstname = $db->santizeInput($firstname);
    $secondname =$db->santizeInput($secondname);
    $email =$db->santizeInput($email);
    $phonenumber = $db->santizeInput($phonenumber);
 
    if (checkLength($firstname) && checkLength($secondname))
    {	
	$sql = "insert into User (firstname, lastname, email, phoneNum) values (\"$firstname\",\"$secondname\",\"$email\", \"$phonenumber\")";
	$db->insertData($sql);
	echo "Data inserted";
    }

I did write within the exercise that since someone may try and post the data to the server within using the webpage (naughty people that they are!!) you could also check the inputs again for there data validity.

Here is the full code for the web page in total.

<?php
    class databaseAccess
    {
      private $dbLink;
      /* connect to the database*/
      function __construct($host = "localhost", $user = "user", $password = "password", $database = "database")
      {
	$this->dbLink = mysql_connect($host, $user, $password);
	if (!$this->dbLink) die("no database present");
	if (!mysql_select_db($database, $this->dbLink))
	  die("no database within the database");
      }
 
      /* disconnect */
      function __destruct()
      {
	if (!$this->dbLink) mysql_close($this->dbLink);
      }
 
      /* santize the input for a mysql database */
      public function santizeInput($theStr)
      {
	return trim(stripslashes(mysql_real_escape_string($theStr)));
      }
 
      /* insert the data into the database */
      public function insertData($sqlData)
      {
	mysql_query($this->santizeInput($sqlData), $this->dbLink) or die("Error inserting data");
      }
    }
 
    function checkLength($theStr)
    {
      if (strlen($theStr) > 0) 
	return true; 
      else 
	return false;
    }
 
    // could use foreach loop $_POST inputs, but I personally prefer to pick them up.
    $firstname = $_POST['firstname'];
    $secondname =$_POST['secondname'];
    $email = $_POST['email'];
    $phonenumber = $_POST['phonenumber'];
 
    /* could do additional checks on input incase it is sent via backend POST and not via the webpage, not sure if SOAP are looking for that as well ? 
      could do with regular expression as well ? */
    $db = new databaseAccess("localhost", "User", "PW", "Test");
    /* can santize the inputs to make sure that there is some data to "play" with */
    $firstname = $db->santizeInput($firstname);
    $secondname =$db->santizeInput($secondname);
    $email =$db->santizeInput($email);
    $phonenumber = $db->santizeInput($phonenumber);
 
    if (checkLength($firstname) && checkLength($secondname))
    {	
	$sql = "insert into User (firstname, lastname, email, phoneNum) values (\"$firstname\",\"$secondname\",\"$email\", \"$phonenumber\")";
	$db->insertData($sql);
	echo "Data inserted";
    }
 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script language="javascript">
  /* check the length of the element, focus is none present */
  function lengthCheck(elem, thename)
  {
    if (elem.value.length> 0) 
      return true;
    else
    {
      alert("Please insert the " + thename);
      elem.focus();
    }
  }
 
  /* check a email address, using regular expression */
  function emailChecker(elem)
  {
    var reg = /^[\w\-\.\+]+\@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (elem.value.match(reg))
      return true;
    else
    {
      alert ("Please insert a valid email address");
      elem.focus();
      return false;
    }
  }
 
  /* check against a phone number. a number being between 11-15 numbers*/
  function checkPhone(elem)
  {
    var reg = /^[0-9]{11,15}$/;
    if (elem.value.match(reg))
      return true;
    else
    {
      alert ("Please insert a valid phone number");
      elem.focus();
      return false;
    }
  }
 
  function checkInputs()
  {
    // obtain inputs
    var firstname = document.getElementsByName("firstname").item(0);
    var secondname = document.getElementsByName("secondname").item(0);
    var email= document.getElementsByName("email").item(0);
    var phonenum = document.getElementsByName("phonenumber").item(0);
    /* check the inputs */
    if (lengthCheck(firstname, "first name")) 
      if (lengthCheck(secondname, "second name"))
	if (emailChecker(email))
	  if (checkPhone(phonenum))
	    return true;
    return false;
  }
</script>
</head>
<body>
<form name="input" action="insertData.php" method="post" onSubmit="return checkInputs()">
First Name :
<input type="text" name="firstname"/>
 
Second Name : 
<input type="text" name="secondname"/>
 
Email : 
<input type="text" name="email"/>
 
Phone number : 
<input type="text" name="phonenumber"/>
 
<input type="submit" value="Submit"/>
</form>
</body>
</html>

If you save that as insertData.php then open up within your web-server. You will be able to insert data into a database with some javascript / php checks.

Web page inputs and insert into database

Also from the other posts, Join files together and simple calculator , I was also asked to do

“Accept form input for a user registration form, and store results in a MySQL table, using PHP. Applicant should demonstrate a knowledge of input validation, and using server-side code to avoid sql injection exploits. The user data should include first name, last name, email, an phone number.

Usage of Javascript pre-validation would be a plus, as would forward planning, i.e. adding a unique code to the user details that could be used to validate their email address. Suitable MySQL table schema should be demonstrated.”

To start with, I started at the data insert within a web page

<body>
<form name="input" action="insertData.php" method="post" onSubmit="return checkInputs()">
First Name :
<input type="text" name="firstname"/>
Second Name : 
<input type="text" name="secondname"/>
Email : 
<input type="text" name="email"/>
Phone number : 
<input type="text" name="phonenumber"/>
<input type="submit" value="Submit"/>
</form>
</body>

Which takes in the required input’s and also within the form HTML tag, but before sending to the back end PHP part of the exercise, there was a requirement to do some Javascript checking on the inputs.

So here is the javascript that will check the inputs, within the form onsubmit action I call this function checkInputs and the return value (true/false) is returned which gives the form either a action to post back to the server (true return) or to wait for the user correct there inputs (false return).

    var firstname = document.getElementsByName("firstname").item(0);

I get the data from the webpage, getElementsByName (which since it is a name there could be x amount of elements with that name, so I want the first one (.item(0))

  function checkInputs()
  {
    // obtain inputs
    var firstname = document.getElementsByName("firstname").item(0);
    var secondname = document.getElementsByName("secondname").item(0);
    var email= document.getElementsByName("email").item(0);
    var phonenum = document.getElementsByName("phonenumber").item(0);
    /* check the inputs */
    if (lengthCheck(firstname, "first name")) 
      if (lengthCheck(secondname, "second name"))
	if (emailChecker(email))
	  if (checkPhone(phonenum))
	    return true;
    return false;
  }

and then after getting the elements, I then call different additional functions that I did write within javascript to check the inputs gained. Here I check the length of a element passed within the one of the parameters within the function parameter list, with using objects you can access the objects value.length (javascript object of a element) and also use the focus function with the element which will focus the element on the webpage for the user to know where to check there input (also with a alert window to say why, e.g. “please insert some data”.)

  function lengthCheck(elem, thename)
  {
    if (elem.value.length> 0) 
      return true;
    else
    {
      alert("Please insert the " + thename);
      elem.focus();
    }
  }

Here is a way of using regular expression to check email inputs, basically it first checks to make sure there is a name before the “@” and also a at between 2 and 4 names with a “.” better them.

  /* check a email address, using regular expression */
  function emailChecker(elem)
  {
    var reg = /^[\w\-\.\+]+\@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (elem.value.match(reg))
      return true;
    else
    {
      alert ("Please insert a valid email address");
      elem.focus();
      return false;
    }
  }

Here is a similar way as above for checking a phone number input between 11-15 numbers

  /* check against a phone number. a number being between 11-15 numbers*/
  function checkPhone(elem)
  {
    var reg = /^[0-9]{11,15}$/;
    if (elem.value.match(reg))
      return true;
    else
    {
      alert ("Please insert a valid phone number");
      elem.focus();
      return false;
    }
  }

This is the web page part, and here is the second part where I insert the data into database with php.

But here is the full web page part of the first part.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script language="javascript">
  /* check the length of the element, focus is none present */
  function lengthCheck(elem, thename)
  {
    if (elem.value.length> 0) 
      return true;
    else
    {
      alert("Please insert the " + thename);
      elem.focus();
    }
  }
 
  /* check a email address, using regular expression */
  function emailChecker(elem)
  {
    var reg = /^[\w\-\.\+]+\@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (elem.value.match(reg))
      return true;
    else
    {
      alert ("Please insert a valid email address");
      elem.focus();
      return false;
    }
  }
 
  /* check against a phone number. a number being between 11-15 numbers*/
  function checkPhone(elem)
  {
    var reg = /^[0-9]{11,15}$/;
    if (elem.value.match(reg))
      return true;
    else
    {
      alert ("Please insert a valid phone number");
      elem.focus();
      return false;
    }
  }
 
  function checkInputs()
  {
    // obtain inputs
    var firstname = document.getElementsByName("firstname").item(0);
    var secondname = document.getElementsByName("secondname").item(0);
    var email= document.getElementsByName("email").item(0);
    var phonenum = document.getElementsByName("phonenumber").item(0);
    /* check the inputs */
    if (lengthCheck(firstname, "first name")) 
      if (lengthCheck(secondname, "second name"))
	if (emailChecker(email))
	  if (checkPhone(phonenum))
	    return true;
    return false;
  }
</script>
</head>
<body>
<form name="input" action="insertData.php" method="post" onSubmit="return checkInputs()">
First Name :
<input type="text" name="firstname"/>
 
Second Name : 
<input type="text" name="secondname"/>
 
Email : 
<input type="text" name="email"/>
 
Phone number : 
<input type="text" name="phonenumber"/>
 
<input type="submit" value="Submit"/>
</form>
</body>
</html>

AJAX – setup and test

AJAX is the way of communicating with a back end server without having to send the full information (you can of course) but for example you could just send a username check to see if it is available, but the main thing is that you do not send back a full page but only the part that you want to update.

With reference to the example of a username, you could just send the username and send back either yes or no response which saves allot of time and traffic from the client to the server (and makes the whole web page experience nicer).

All the AJAX is shorthand for “Asynchronous JAvascript and Xml”, asynchronous means that you can do something else whilst waiting for the response (put the kettle on and get a cup for the drink whilst the kettle is boiling) thus with javascript on the client web browser sends a request to a web page on the server with XML wrappings.

To get the basics lets start with the being

  // this function will return a XmlHttpRequest object that allows you to "talk" to the server.
  function GetXmlHttpObject()
  {
      // IE7+, FF, Chrome, Opera, Safari
      if (window.XMLHttpRequest) return new XMLHttpRequest;
 
      // IE6 , IE5
      if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  }

the GetXmlHttpObject will return a object that will allow the javascript to talk to the backend server, the newer version is call a XMLHttpRequest whilst on older browsers it was part of the ActiveXObjects.

The next is to send a request to the backend server

    xmlHttpObject.onreadystatechange=callBackFunction;
    xmlHttpObject.open("GET", GetUrl, true);
    xmlHttpObject.send(null);

The onreadystatechange, will call a function (in javascript on the client browser) when the request alters from different states, the different states are

  • 1.open method invoked successful, open a connection with the server
  • 2.server responsed with a valid header response.
  • 3.server has sent some data, the response content is started to load.
  • 4.server has finished sending all of data

so from reading the states, you are really interested in state 4, because that will have the data (server response) that you are interested in for this.

The .open forms the request to the XmlHttpRequest object to call (“GET” in HTML) the server web site, the GetUrl is just a variable that well call a php page (“ajaxbackendcall.php”) which takes a parameter called name and returns a string with the name in reverse (shall include that source code later).

And then the .send will start the ready states to change and sends the request to the backend server, here is the function that is called on the state change

  function callBackFunction()
  {
    if (xmlHttpObject.readyState == 4)
      alert(xmlHttpObject.responseText);
  }

What is happening here, is that from the state stages I am waiting on ready state to equal 4 ( when the server has finished responding) and then output the response from the responseText which is filled from the AJAX call to the backend server.

That is mainly it, here is some full code for you to try out save this as “codingfriends.com.ajax.test.html”

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html3/strict.dtd">
<html>
<head>
<script type="text/javascript">
  // the xmlHttpRequest object
  var xmlHttpObject;
 
  // the ajax call 
  function getInnerText()
  {
    // get the name to send to the server backend page
    var namehere = document.getElementById("namehere");
 
    // request the xmlHttpObject 
    xmlHttpObject = GetXmlHttpObject();
 
    // if there is not xmlHttpRequest object being allowed to be created then the browser does not support it.
    if (xmlHttpObject==null)
    {
      alert("Browser does not support XmlHttp calls e.g. AJAX");
      return;
    }
 
    // fill in the request details, e.g. the url to call and also the query string inserted into the url
    var GetUrl = "ajaxbackendcall.php"+"?name="+namehere.value;
 
    // here is the call to the server.
    // to start with setup which function to call when a ready state on the XmlHttpRequest object has changed
    xmlHttpObject.onreadystatechange=callBackFunction;
    // request the html "GET" to obtain the url (e.g. the backend server page, dynmaic normally)
    xmlHttpObject.open("GET", GetUrl, true);
    // and then issue it
    xmlHttpObject.send(null);
  }
 
  // the function that is called once the XmlHttpRequest object state has changed
  /* the readyStates are 
    1 open method invoked successful, open a connection with the server
    2 server responsed with a valid header response.
    3 server has sent some data, the response content is started to load.
    4 server has finished sending all of data
  */
  // so we listen for readyState 4 when all finished
  // and output the response text into the div id innertextoutput
  function callBackFunction()
  {
    if (xmlHttpObject.readyState == 4)
      document.getElementById("innertextoutput").innerHTML=xmlHttpObject.responseText;
  }
 
  // this function will return a XmlHttpRequest object that allows you to "talk" to the server.
  function GetXmlHttpObject()
  {
      // IE7+, FF, Chrome, Opera, Safari
      if (window.XMLHttpRequest) return new XMLHttpRequest;
 
      // IE6 , IE5
      if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  }
</script>
</head>
<body>
<a href="#" onclick="javascript:getInnerText()">click here to return text from a ajax call</a>
<br/>
Enter the name here <input id="namehere"/>
<br/>
<div id="innertextoutput"></div>
</body>
</html>

and then save this as the ajaxbackendcall.php file to call (in the same directory as the code above and also within a directory that has PHP plugin enable for that webserver be it apache or IIS.

<?php
    $name = $_GET['name'];
 
    // change the output to say something else, here I am just reversing the name
    if (strlen($name) > 0)
    {
      // have to insert something into it so that php does not make it into a array but a string
      $namereturn="0";
      $j = 0;
      for ($i = strlen($name)-1; $i >= 0; $i--)
      {
        $namereturn[$j++]=$name[$i];
      }
      echo "normal name {$name} and in reverse {$namereturn}";
    }
    else
      return "No name inputted";
?>

The output would be similar to the below. OUTPUT

click here to return text from a ajax call
Enter the name here

END OF OUTPUT

If you do not have a PHP webserver to test with, you can just alter the codingfriends.com.ajax.test.html code by altering the backend web page to call to this

var GetUrl = "nonephpbackend.html"

and create a page within the same directory as the codingfriends.com.ajax.test.html page and place something inside it like

hi there

hover over to show a hidden element

Sometimes you may not have the luxury of having javascript to do some of the great things that it can do, like showing hidden content on the screen when you hover over a HTML element (like a A HTML tag for example). In CSS you can achieve a similar result with using some of the overflow and styling elements of un/ordered lists to accomplish a similar result.

If you save this code as codingfriends_showhide.html and then open it up in Firefox or your browser of choice (not sure if it will work in IE6 shall have to check it !). and then just hover over the block and it will display the hidden message 🙂

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>CSS - show/hide on hover</title>
<style type="text/css">
/* the main ul block, there is no list style at all e.g. all together */
#showhideblock {
	list-style:none;
	margin:0;
	padding:0;
}
/* the main ul block elements push to the left and make there display inline e.g. no breaks */
#showhideblock li {
	float:left;
	width:200px;
	height:55px;
	display:inline;
	border:1px solid black; 
}
 
/* the basic showing element of the list */
#showhideblock li .show{
	display:block;
	width:200px;
	height:55px;
}
/* hide the hiding element of the list with the height of 0 and overflow set to hidden */
/* but once shown display in black */
#showhideblock li .hide {
	color : black;
	height: 0; /* hide the .hide element */
	overflow: hidden;
	background:black;
}
/* when you hover over the shown element, set the hidden element sizes */
#showhideblock li:hover .hide, #showhideblock li.over .hide {
	height: 55px;
	width:  200px;
}
/* when you hover over the shown element set the shown element height and overflow values */
#showhideblock li:hover .show, #showhideblock li.over .show {
	height: 0;
	overflow: hidden;
}
 
/* set the show a href links to colour of black (on the white background of the shown element */
/* and the textual size to be bigger than normal */
#showhideblock li a {
	color:black;
	font-size:1.5em;
}
/* since changing the background colour of the hidden element to black, change the on hover */
/* to have a textual colour of white */
#showhideblock li a:hover {
	color:white;
}
</style>
</head>
 
<body>
<ul id="showhideblock">
    <li>
      <a class="show" href="#"  title="The image to show">Hover over me, what has been hidden ?</a>
      <div class="hide">
	<a href="#" title="the hidden link">Codingfriends - I was hidden here all along</a>
      </div>
    </li>
</ul>
</body>
</html>

In essence the main parts of the code are as follows, you need to set the unordered list to have a list style of none with the list elements (li) having a display of being inline (which means that there is no breaks between the elements).

#showhideblock {
	list-style:none;
...
#showhideblock li {
	display:inline;

with this in place you can use the size of show and hide elements with also the overflow set to hidden (when you hover over the block you need to set the shown element overflow to hidden and set the size of the hidden element so that it shows)

#showhideblock li .hide {
	color : black;
	height: 0; /* hide the .hide element */
	overflow: hidden;

And once you have saved the above file and opened up in your browser of choice when you now hover over the “Hover over me” text you will see the hidden text instead.

Java applet – hello world

A java applet is a web object that allows you to do some funky things within a web page, you could even have a game on the screen with a java applet. But as normal you have to start from the start as such, the most used starts are the classic “hello world” example.

In a java applet, it is basically a class called Applet that you extend from and this has all of base code inside it so you only need to implement the virtual functions

  1. init
  2. start
  3. paint
  4. destory
  5. stop

And these are the basic functions that allow you to call other classes of your choice. The init – (initialize), setups up the environment of your choice, start is where the application (GUI interface) will run within, paint is what is painted to the applet screen, destory is when you destory the applet you may need to clean up some code, stop is when the application/applet is stopped.

The main basic class will extend from a applet (java.applet.Applet) so you will need to import that class library

import java.applet.Applet;
 
// basic class extends the applet
public class HelloWorld extends java.applet.Applet {

and then implement the functions start,init,stop,destory and paint if required. Below is more code that will resize the basic applet object and display (paint) the words Hello World using the Graphics class object drawString method.

import java.awt.Graphics;		// need this for the Graphics part of the paint function
import java.applet.Applet;		// to extend from.
 
public class HelloWorld extends java.applet.Applet {
 
    // resize the screen 
    public void init()
    {
	resize(150,25);
    }
 
    public void start()
    {
    }
 
    // draw with the Graphics class object a string on the canvas, point 50, 25
    public void paint(Graphics graphicsObj)
    {
	graphicsObj.drawString("Hello World!", 50,25);
    }
 
    public void stop()
    {
    }
 
    public void destroy()
    {
    }
}

Is you save that as “HelloWorld.java” and then you need to compile it into a class file (which is a common object file that java can read to run within the virtual machine).

javac HelloWord.java

which will output the HelloWorld.class file, which you will need to include into the html code applet tag, below is the HTML code

<HTML>
<head>
<title>A hello world</title>
</head>
<body>
Test output of the program
<applet code="HelloWorld.class" width=150 height=25>
</applet>
</body>
</HTML>

The output would be

Test output of the program

Note: If you look at the source code of this page, it will say

<applet code="HelloWorld.class" codebase="/Appletsexamples/"  archive="HelloWorld.jar" width="150" height="25"></applet>

I had to add in the codebase and archive because of the hosting, to create a jar file you just need to do

jar cf <tarname> <file(s) name>
 
jar cf HelloWorld.jar HelloWorld.class

The jar file is basically a zipped archive.