Page 1 of 1

Introduction to Java Applets Rate Topic: ***** 1 Votes

#1 v0rtex  Icon User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Posted 24 April 2011 - 04:50 AM

*
POPULAR

Introduction to Java Applets:

Java was originally the first language that could run inside a web browser, this ability of java has made it famous and also allowed others to knock its programming prowess as it was deemed good for this purpose and this purpose only by some. The method that java used to run programs inside a web browser was by way of an applet.

A java applet is quite simply a program designed to run as part of a web page. When one encounters a java applet on the web, the applet is downloaded and begins running on the webpage. A good example of a java applet would be http://java.sun.com/...k/example1.html
(Ignore the code on that site for now, just focus on the clock example)

The applet itself is executed by the browser’s Java Virtual Machine (JVM).

Programming applets is rather different to coding a standard java program as the code must be adjusted to run on a webpage, this is most noticeable by not having a standard main method:
 public static void main(String[] args) 

as will be demonstrated later. An Applet also requires a HTML (Hyper Text Markup Language) page to be setup in order to have a webpage to run on.

A java applet is created firstly by making it a subclass of JApplet, which is a class in the Swing package (javax.swing). When you create a subclass of JApplet, your applet will have everything it needs to interact with a web browser and be run inside a HTML page. One would create a subclass of JApplet like so:
Import javax.swing.*; //make all classes from the swing package available
Public class Skeleton extends JApplet {
//Applet code will be coded in this method
}


Note: The subclass of JApplet must be public as JApplet is public however like normal, other class files that are used do not have to be.
A java applet has no standard main() method. Instead it has a series of methods that are there to handle various events that could occur in your applet. The most used methods/functions are:
  • Init() and start(): These methods are called when the program is first loaded. Due to init() being called first, it is generally where programmers set up variables that are used.

  • paint(): This method is required to display the various graphical elements of your applet. Should the programmer code something that requires for the applet to be redisplayed, then repaint() can be called. repaint() in simple terms refreshes the applet
.
  • stop(): This method is called should the applet be stopped by the browser or the user.

  • start(): This method is used to restart the method after it has been stopped.

  • destroy(): This method is used to free the memory used by the java applet

The methods described above are automatically inherited by your JApplet class however none of these methods do anything as such. The programmer needs to code the above methods to fulfill their purposes described above. Not all the methods described above must be used in a Java Applet.
Our first Java Applet – Hello World:
import java.awt.*;
import javax.swing.*;
public class HelloWorld extends JApplet {
String message; //declare string greeting here so that it has scope to be used for both init() and paint() methods
    public void init() { //automatically called when applet is started.
    message = "Hello World!"; //set text of String message
    }
    public void paint (Graphics screen) { //called automatically by init() to draw graphical elements on the screen
        Graphics2D screen2D = (Graphics2D) screen; //explained below code
        screen2D.drawString(message, 25, 50); //explained below code
    }
}



The first few lines are rather self-explanatory with the comments however the paint method is a little bit trickier. The paint() is called when something requires the applet to be refreshed. This “something” can be from the OS or the user using the browser itself. Say a user was to shrink the browser window, the paint() method must be called to shrink the applet’s graphical elements accordingly.

public void paint(Graphics screen) {
Graphics2D screen2D = (Graphics2D) screen;



The Graphics class is a “graphical context”, a “graphical context” is an environment in which something can be displayed. The screen object of the Graphics class in line 2 is cast into a Graphics2D object. The Graphics2D object is from the Swing package and it is necessary to do this to use the Swing methods associated with graphics. The Graphics and Graphics2D classes are from the java.awt.* package, you can import them via one of the following:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.*;



 screen2D.drawString(message, 25, 50); 


The above line of code draws the String message onto the applet window:
  • The first argument passed (message) handles the String to display.

  • The second argument passed (25) handles the x position of the String to be displayed.

  • The third argument passed (50) handles the y position of the String to be displayed.

Note: The (x,y) co-ordinate system of a Java Applet starts at the top right corner with (0,0), if you go to the right, the x co-ordinate increases and if you go down the y value increases.

Okay after that explanation, how do we display our code on a webpage?
In order to do this, a HTML page must be created. The code below is how we are going to test our java applet:
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<p>This is your first java applet shown below! </p>
<applet
     code ="HelloWorld.class" 
    codebase="..\\..\\build\\classes" 
    height="150" 
   width="300" 
  <p>You need a java-enabled browser to see this.</p>
 </applet>
</body>
</html> 


If you are familiar with HTML then you can skip the brief HTML explanation below:
HTML’s commands are known as tags that are surrounded by < and > symbols. Tags starts with <tag> and end with </tag>. An example would be <body> and </body>. Tags are structured like follows:
<element attribute> </end of element>


A element is a browsing command. An attribute is the properties of the element that further instruct the browser. An example would be the applet tag
<applet
     code ="HelloWorld.class" 
    codebase="..\\..\\build\\classes" 
    height="150" 
   width="300" 
  <p>You need a java-enabled browser to see this.</p>
 </applet>



The first attribute of the applet tag (code) describes the name of the applet’s class file.
The second attribute (codebase) contains the path of the class file
The third attribute (height) sets the height of the applet in the browser window in terms of pixels.
The fourth attribute (width) sets the width of the applet in the browser window in terms of pixels.

The paragraph tag <p>You need a java-enabled browser to see this.</p> is only shown if the applet is unable to be run as the user’s browser does not have the java plug-in installed. </applet ends the applet tag.
Some basic and necessary tags to know in order to understand the HTML we will use for our applet are:

  • <html> - Begins your HTML document.

  • <head> - Contains information about the page such as the TITLE, META tags for proper Search Engine indexing, STYLE tags, which determine the page layout, and Javascript coding for special effects.

  • <title> - The TITLE of your page. This will be visible in the title bar of the viewers’ browser.

  • </title> - Closes the HTML <title> tag.

  • </head> - Closes the HTML <head> tag.

  • <body> - This is where you will begin writing your document and placing your HTML codes.

  • </body> - Closes the HTML <body> tag.

  • </html> - Closes the <html> tag.

(referenced from: http://www.web-sourc...odes_chart.htm)
If you wish to do more reading on HTML, see the Dream In Code tutorials or visit: http://www.web-sourc...codes_chart.htm
If you then save and run our HTML page for the HelloWorld Java Applet code above, you should get the following:

Posted Image

Now, that you have displayed your first Java applet.
You may be wondering how do you send and recieve parameters from a webpage so that you can work with your HTML document?

The way to do this is rather simple and it offers many benefits to your applet as your applet's results can depend upon the parameters in the web page. You would declare a parameter like so:

<param name="user" value ="Person">


The above code creates a parameter called viewer and sets its value to "Person".
Now that you have made the parameter, how then in Java can you receive the parameter from the webpage?
The solution to this is also simple, the java.awt.* package has a getParameter(String parameterName) method which will return the value of the entered parameter.
This would be achieved like so:
String userParameter = getParameter("user");
if (userParameter != null) { txtCurUser = userParameter; }



The reason for the above if statement is so that if the parameter is null or not found, we do nothing. If it is then we set our String value for txtViewer (Full listing below) and print the value of the HTML Parameter viewer.

Full listing for modified HelloWorld.java:


import java.awt.*;
import javax.swing.*;
public class HelloWorldModified extends JApplet {
String message; int txtCurUser;//declare string greeting here so that it has scope to be used for both init() and paint() methods
    public void init() { //automatically called when applet is started.
    message = "Hello World!"; //set text of greeting
String userParameter = getParameter("userAge");
if (userParameter != null) { txtCurUser =  Integer.parseInt(userParameter); }
    }
    public void paint (Graphics screen) { //called automatically by init() to draw graphical elements on the screen
        Graphics2D screen2D = (Graphics2D) screen;
        screen2D.drawString(message, 25, 50);
        screen2D.drawString("Age of person viewing this page:" + txtCurUser, 35, 70);
    }
}



And the full text of the modified HelloWorld.html:
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<p>This is your java applet that handles parameters! </p>
<applet
     code ="HelloWorldModified.class"
    codebase="..\\..\\build\\classes"
    height="150"
    width="300">
   <param name ="userAge" value="20">
  <p>You need a java-enabled browser to see this.</p>
 </applet>
</body>
</html>



I hope you have enjoyed my tutorial and that you now have a basic understanding of how Java Applets function and work :)
Challenge (for those new to Java Applets):
  • Change the colour of the background of the HTML Page

  • Create a java applet that displays Integer, String and Float Parameters.


Thanks,
v0rtex

This post has been edited by v0rtex: 30 April 2011 - 12:50 AM


Is This A Good Question/Topic? 11
  • +

Replies To: Introduction to Java Applets

#2 codewizard  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 16
  • Joined: 20-April 11

Posted 01 May 2011 - 05:14 AM

Very helpful, thanks. Can you perhaps do a tutorial on Game programming?
Was This Post Helpful? 0
  • +
  • -

#3 v0rtex  Icon User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Posted 01 May 2011 - 05:22 AM

I might do some tutorials on Game Programming with Java using the Java3D API but for now you may want to look at dogstopper's or ButchDean's game programming tutorials, also macosxnerd101's Game Math tutorials could help you, basically just look through: http://www.dreaminco...ming-tutorials/
for now, I might work on some Game Programming tutorials later :)
Was This Post Helpful? 0
  • +
  • -

#4 jgonzalez498  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 43
  • Joined: 29-May 11

Posted 02 June 2011 - 06:01 PM

Nice! Well explained information but the thing I don't understand is there things people call parameters? D: why do we use them inside the html file like what good does it benefit the applet displaying in the web browser and if you could reference me somewhere to even learn what a param is it'd be super appreciated.
Was This Post Helpful? 0
  • +
  • -

#5 v0rtex  Icon User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Posted 02 June 2011 - 09:44 PM

Parameters in their simplest form are simply variables that are passed between programs or methods. In this case we are using parameters in our HTML code so that what the user does will have a result in our HTML program which will then be acted upon in our Java program, it is needed in many instances for example if you want the user to enter some data (name,age etc...) which you then display in your applet. You would need to pass the data as variables to your applet and then could display them in a String type for example.

Here you can see we declare a parameter called name and set its value to 20:

 <param name ="userAge" value="20">



This is then recieved in our Java program by first fetching the parameter and then parsing it to a data type which in this case is a integer:
String userParameter = getParameter("userAge"); //getParamer in HTML called userAge' value
	if (userParameter != null) { txtCurUser =  Integer.parseInt(userParameter); }



Hope this helps, otherwise post a question in the Java forum.

This post has been edited by v0rtex: 02 June 2011 - 09:46 PM

Was This Post Helpful? 0
  • +
  • -

#6 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 116
  • View blog
  • Posts: 1,358
  • Joined: 14-January 10

Posted 04 June 2011 - 02:34 PM

An interesting problem I have found is that on Mac when you look at an applet it thinks of it as a plug in. So on my Mac it thinks that I have a plug in missing and won't show me the applet.
Was This Post Helpful? 0
  • +
  • -

#7 v0rtex  Icon User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Posted 05 June 2011 - 01:31 AM

@ RandomlyKnighted:

Are you on Mac OS X?

If so and your default jdk is Java 6 SE, try typing this into terminal:
appletviewer http://www.example.com/applet.html


Where the URL is the destination for your applet, just check URL at top when you attempt to run in the browser.

I have never really utilized Mac myself however, this blog post may help:
Link

Hope this helps,
v0rtex

This post has been edited by v0rtex: 05 June 2011 - 01:33 AM

Was This Post Helpful? 0
  • +
  • -

#8 varsha0802  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 22
  • Joined: 16-October 10

Posted 05 June 2011 - 07:48 AM

Very helpful tutorial.

I have a doubt:

View Postv0rtex, on 24 April 2011 - 04:50 AM, said:

Note: The (x,y) co-ordinate system of a Java Applet starts at the top right corner with (0,0), if you go to the right, the x co-ordinate increases and if you go down the y value increases.


Shouldn't it be the top left corner?
Was This Post Helpful? 1
  • +
  • -

#9 v0rtex  Icon User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Posted 05 June 2011 - 01:03 PM

Yes, cant believe I missed that :/ Will edit, thanks.
Was This Post Helpful? 0
  • +
  • -

#10 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 116
  • View blog
  • Posts: 1,358
  • Joined: 14-January 10

Posted 06 June 2011 - 07:23 PM

I'm sorry but IMO it's kind of stupid that you have to do that for every applet if you are using Mac OS X.
Was This Post Helpful? 0
  • +
  • -

#11 v0rtex  Icon User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Posted 06 June 2011 - 09:29 PM

I have no control over how the developers made Java... There are most likely ways around this applet problem on the Mac OSX. Google it or ask in the Java forum bud :)
I wish I could be more help but I have no experience with Mac, so...

This post has been edited by v0rtex: 09 June 2011 - 09:25 AM

Was This Post Helpful? 0
  • +
  • -

#12 cloverasx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 22-April 12

Posted 22 April 2012 - 04:23 PM

I don't quite understand the codebase term... is it necessary if the html file is located in the same folder as the class? and where does it begin? I have it now as C:\users\myusername\Documents\Android Development\JAVA\JavaProjects\Applet and I can't get the applet to run... thanks in advance for the help.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1