Jump to content
xisto Community
FearfullyMade

Java Applets how to make an applet in Java

Recommended Posts

The purpose of this tutorial is to explain how to create a Java applet. A Java applet is simply a Java program that runs on a webpage. This tutorial assumes that you have a basic understanding of Java. If you don't, I would suggest reading a tutorial on Java first.

 

In this tutorial I will be using Java 1.5 (or 5.0). If you don't have it you can download it from Sun. The classes and methods used in this tutorial may work for other versions of Java, but I don't know for sure.

 

During this tutorial I would suggest opening up Java's online documentation, found here, so that you can look at the classes and methods I use and see what they do for yourself. One of the best ways to learn about Java is the explore the documentation.

 

The JApplet Class

 

Like every Java program, an applet requires you to have at least one class. Luckily for us, the guys at Sun made creating applets pretty easy by designing a simple framework class for us to use: JApplet. This class gives all the functionality that you need. All you need to do is create a class that extends JApplet and you are well on your way. Be sure to import the package that contains JApplet, javax.swing.

 

import javax.swing;public class Bouncy extends JApplet{    //the code for your applet goes here}

The JApplet class has many, many different methods, but there are only a few main ones that are really important. These methods are called by Java when certain events occur. Here they are along with an explanation:

 

init() - This method is automatically called when a user first accesses the page that contains your applet. You can think of it the applet's version of the main() method. Here is where you put all of your one-time initialization code, hence the name.

 

start() - While your applet is only initialized once, it can be started and stopped many times. When the user leaves your applet's page the applet stays in memory. The stop() method is called (see below) but nothing else happens. Normally your applet will not actually be shut down until the browser is completely closed. The start() method is called both the first time your applet is loaded, right after init(), and whenever the user returns to your page. You can use this method to start your applet's action or do any initialization that needs to happen every time the users goes to the page.

 

stop() - This is called whenever the user leaves the applet's page. You don't want to uninitialize everything in this method because they could return to your applet. Use this method to stop any actions that your applet may be doing.

 

destroy() - This is the last method that Java calls. It is called just before the applet is shut down. Here is where you need to uninitialize and close anything you have running.

 

 

You are not required to included all of these in your class, only include the ones you need. You will need to have at least one of them, otherwise your applet will never do anything!

 

 

The Timer class

 

The timer class doesn't really have anything to do with applets, but since I need it in my example applet, I'll take a moment to explain the basics of how it works. If you already know how it works or just don't care feel free to skip this section.

 

The Timer class allows you to schedule tasks to occur. There are several different methods used to schedule tasks, but the one we're interested in right now is the one that repeats the task every x milliseconds, schedule(TimerTask timer, long delay, long period). The delay is how long to wait before beginning and the period is the frequency that the task is carried out.

 

TimerTask is a class that describes what to do when your task needs to be done. Whenever the Timer class sees that it is time to do a task it calls the run() method of the corresponding TimerTask class. Since the only important part of the TimerTask class is the run() method you can define the class right when you create an object of it, like I do.

 

So, here is the code that would create a timer and schedule a task to begin immediately and to go off every 50 milliseconds:

 

Timer timer= new java.util.Timer();TimerTask task= new TimerTask() { public void run() { /* do stuff in here*/ } };timer.schedule( task , 0, 50);  

When you are done with the task call its cancel() method and when you are done with the entire timer call its cancel() method.

 

task.cancel();timer.cancel();

Putting it together

 

Now that you understand how applets work it is time to make one. The example below is just a simple applet where a ball bounces around. It is pretty straightforward. You can see it in action here. I use the four methods I talked about earlier along with one of my own, move(), which moves the ball. I used the timer code I showed earlier, split up and put into the correct methods.

 

import javax.swing.*;import java.util.*;import java.awt.*;public class Bouncy extends JApplet{    //position of the ball    int x,y;    //direction the ball is moving    int deltaX, deltaY;    final int RADIUS = 20;  //size of ball    final int SPEED = 10;  //speed the ball is moving    //used to update the balls position    java.util.Timer timer;    TimerTask task;        public void init()    {        //these are the things that only need to be started once        //set balls position        x=200;        y=150;        //set the balls direction        deltaX=2*SPEED;        deltaY=SPEED;        //create the timer        timer= new java.util.Timer();	    }    public void start()    {          //the timer needs to be started everytime the page is loaded        //the run() method of this class will be called by the timer at the specified interval        task= new TimerTask() { public void run() { move(); } };	        timer.schedule( task , 0, 50);  //start timer    }    public void stop()    {        //stop the task when the user leaves the page        task.cancel();        timer.purge();	    }    public void destroy()    {        //get rid of the entire timer when we are done        timer.cancel();    }    public void move()    {        ///move ball        x+= deltaX;        y+= deltaY;	        //cange direction if it hits the wall        if ((x-RADIUS) <= 0)            deltaX*= -1;        else if ((x+RADIUS) >= getWidth())            deltaX*= -1;        if ((y-RADIUS) <= 0)            deltaY*= -1;        else if ((y+RADIUS) >= getHeight())            deltaY*= -1;	        //draw        Graphics g= getGraphics();        //clear background        g.setColor(Color.GREEN);        g.fillRect(0,0,getWidth(),getHeight());        //draw ball        g.setColor(Color.RED);        g.fillOval(x-RADIUS, y-RADIUS, RADIUS*2, RADIUS*2);    }}

Put it on the web

 

Now that you have the applet, how do you stick it on a web page? The HTML is really pretty easy. There is an applet tag that lets you specify the .class file your applet is in and the size of your applet. Just insert that into a web page and you're ready to go. Don't forget to upload your .class file along with the web page.

 

<html>  <applet code="Bouncy.class" width=300 height=300></html>

 

I hope you found this tutorial useful. Please let me know if you have any comments or suggestions. Also, if you have any questions about Java applets that this tutorial didn't cover let me.

Share this post


Link to post
Share on other sites

@warallthetm, yeah, first you copy it into a normal text file, save as Bouncy.java. And then you need a program to compile it--http://www.oracle.com/technetwork/java/javase/downloads/index.html. (as FearfullyMade said earlier) Then you upload the compiled file--the .class file up onto your website and follow everything else that FearfullyMade said and your applet is all ready to go. Or you can preview with AppletViewer before uploading...that's always very helpful.

Anyways, nice tutorial! This explained it a lot clearer than those textbooks in my Java clas...those were quite very boring and dry. (And their explanations were rather technical than understandable :unsure:)

Edited by Arbitrary (see edit history)

Share this post


Link to post
Share on other sites

couldn't it be easier to use AWT than SWT?


Just a basic I/O script:

import java.applet.Applet;import java.awt.*;import java.awt.event.*;public class finalinput extends Applet implements ActionListener {	public finalinput() {	}	//Declare components	TextField txtDept  = new TextField(15);	TextField txtName = new TextField(20);	TextField txtPhone = new TextField(5);	TextArea txaPhoneList =  new TextArea(10,30);	Button btnAdd = new Button("Add to List");	//Declare variables	String strDept;	String strName;	String strPhone;	public void init()	{		//Place components on applet		add(new Label("Department:		  "));		add(txtDept);		add(new Label("Name:				"));		add(txtName);		add(new Label("Extension:		   "));		add(txtPhone);		add(btnAdd);		add(txaPhoneList);		txtDept.requestFocus();		//Add action listeners		btnAdd.addActionListener(this);		txtDept.addActionListener(this);		txtName.addActionListener(this);		txtPhone.addActionListener(this);	}	public void actionPerformed(ActionEvent event)	{		//Actions for "Add to List"		//Triggered when the user clicks the button or presses the Enter		//Key in any of the text fields		String strOutputLine; //Declare local variable		//Assign the text fields to variabbles		strDept = txtDept.getText();		strName = txtName.getText();		strPhone = txtPhone.getText();		//Concatenate the variables		strOutputLine = strDept + "\t" + strName + "\t" + strPhone;		//Append the concatenated line to the phone list		txaPhoneList.append(strOutputLine + "\n");		//Clear the text fields		txtDept.setText("");		txtName.setText("");		txtPhone.setText("");		//Place the cursor in the first text field		txtDept.requestFocus();	}}

xboxrulz

Share this post


Link to post
Share on other sites

D tutorial was realy helpful..i hv created an analog clock in applet,u can view it on my website http://forums.xisto.com/no_longer_exists/ wil provide dat code 4 others,so dat it cn help others..but i advice programmers to use Jframe instead of applet if u want it to give to a client,it has many benefits..easily coding along with easy event handling..u cn describe various functionality wen u click the exit button...Now i m going to tel d method of composing java archieve file so that u cn send it over net ur projects which comprises grup of classes..just write in ur cmd prompt wid classpath set to jdk's bin directory..now write jar -cvf name.jar *.* nd press enter..here *.* are all project files in ur folder..for making .jar executable file u wil need to add a manifest.txt file wich wil tel which one is main class among group of classes..its code is class Main:classname()..it cn b added to .jar file by jar -cvfm name.jar manifest.txt *.* now d jar files bcomes executable.hope it helpd.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.