Java tutorial - Introduction to applets
Step One - Creating a project
Create a new project, called “AppletDemo”, as explained in the previous lesson. Remember the name of the directory where you create your project - we’ll need this information.
* From the ‘File’ menu, select the ‘New Project’ menu option. Enter a filename, a title, and your name into the Project Wizard dialog box. Click ‘Finish’.
* Next, from the “File” menu, select “Project Properties”, and modify the output path to our project directory.
eg - If your project name was “c:\JBuilder\myprojects\week2\week2.jpr”, your project directory is “c:\JBuilder\myprojects\week2\
Step Two - Creating a source file
An applet is a class that is executed under the control of a world-wide-web browser, such as Netscape Navigator or Internet Explorer. We’ll create a new class, called AppletDemo, that runs as an applet.
* From the ‘File’ menu, select the ‘New’ menu item.
* Select the ‘Class’ option, and click OK.
After clicking OK, the “New Object” dialog box will appear. This allows you to customize the class details. Enter ‘AppletDemo’ in the name field, and ‘java.applet.Applet’ in the extends field. This tells JBuilder that our new class will inherit all the properties of an applet. By default, JBuilder will also put your new classes in the current package - but for the purpose of this tutorial, remove the package declaration. Leave the other fields as they are for now, and click OK.
Step Three - Enter the code
JBuilder automatically creates code for us, but will need to supplement it with out own. Our applet will display a texfield (allowing users to type in a URL), and a button. When a user clicks on the button, the web browser will load the page located at the URL.
Modify the source for AppletDemo.java, until it looks like the following listing, and then build the project.
import java.awt.*;
import java.applet.*;
import java.net.*;
public class AppletDemo extends Applet
{
// Member variables of applet
TextField urlField;
Button goButton;
// Default constructor
public AppletDemo() {
}
// Initialization code for applet
public void init()
{
// Create a text field of size 15 using the 'new' keyword
urlField = new TextField(15);
// Create a new button, labelled Go!
goButton = new Button("Go!");
// Add text field and button to our applet's GUI
add(urlField);
add(goButton);
repaint();
}
public void browse(String url)
{
try
{
AppletContext ac = getAppletContext();
ac.showDocument ( new URL(url) );
}
catch (Exception e)
{
}
}
// Action handlers respond to user interface events
public boolean action(Event evt, Object obj)
{
String location = urlField.getText();
browse (location);
// Return true, since we performed an action
return true;
}
}
