Here's the code for our first Applet which will display 'I love Java' as a message in a Web page



Similar documents
The Basic Java Applet and JApplet

Introduction to Java Applets (Deitel chapter 3)

Java applets. SwIG Jing He

Right now, the latest and greatest version of Java available for download is Start with this link to find out more about it

CSE 452: Programming Languages. Acknowledgements. Contents. Java and its Evolution

How To Write A Program For The Web In Java (Java)

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Essentials of the Java(TM) Programming Language, Part 1

Caldes CM12: Content Management Software Introduction v1.9

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

Hypercosm. Studio.

Chapter 1 Java Program Design and Development

method is never called because it is automatically called by the window manager. An example of overriding the paint() method in an Applet follows:

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

An Overview of Java. overview-1

Visual Basic 6 Error Handling

Interactive Programs and Graphics in Java

WEEK 2 DAY 14. Writing Java Applets and Java Web Start Applications

Java History. Java History (cont'd)

C# and Other Languages

understand how image maps can enhance a design and make a site more interactive know how to create an image map easily with Dreamweaver

Packaging and Deploying Java Projects in Forte

Getting Started with WebSite Tonight

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

CSC 551: Web Programming. Spring 2004

Contents. Java - An Introduction. Java Milestones. Java and its Evolution

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Installing Java. Table of contents

12Planet Chat end-user manual

Using WINK to create custom animated tutorials

Essentials of the Java Programming Language

Action settings and interactivity

With a single download, the ADT Bundle includes everything you need to begin developing apps:

There are some important differences between an applet and a standalone Java application, including the following:

How to install and use the File Sharing Outlook Plugin

WP Popup Magic User Guide

HTML Code Generator V 1.0 For Simatic IT Modules CP IT, IT, IT

Download and Installation Instructions. Java JDK Software for Windows

Your First Web Page. It all starts with an idea. Create an Azure Web App

Using Microsoft Word. Working With Objects

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Banner Frequently Asked Questions (FAQs)

Java is commonly used for deploying applications across a network. Compiled Java code

An Overview of Oracle Forms Server Architecture. An Oracle Technical White Paper April 2000

2. Signer Authentication

HP INTEGRATED ARCHIVE PLATFORM

CS 335 Lecture 06 Java Programming GUI and Swing

Google Sites: Creating, editing, and sharing a site

How To Optimize LANDING PAGES GENERATE MORE LEADS. Tips and Examples From Industry Experts that Will Help Skyrocket Your Landing Page Conversion Rates

Mesa DMS. Once you access the Mesa Document Management link, you will see the following Mesa DMS - Microsoft Internet Explorer" window:

Internet Explorer Settings for Optum CareTracker

TASKSTREAM FAQs. 2. I have downloaded a lesson attachment, but I cannot open it. What is wrong?

Updates to Graphing with Excel

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Installing Java 5.0 and Eclipse on Mac OS X

Anoto pendocuments. User s Guide

Java Software Development Kit (JDK 5.0 Update 14) Installation Step by Step Instructions

Minecraft Server Dashboard Users Guide

A Step-by-Step Patient Guide to Upload Medical Images to the Cleveland Clinic Neurological Institute

WP Popup Magic User Guide

USER MANUAL SlimComputer

Installing the Android SDK

Greetings Keyboard Mastery Keyboarding Students! Teacher: Mrs. Wright

- User input includes typing on the keyboard, clicking of a mouse, tapping or swiping a touch screen device, etc.

Illustration 1: An applet showing constructed responses in an intuitive mode. Note the misprint!

Charms Recording Studio USER GUIDE For PC/Mac As a Parent/Student/Member

THE WINNING ROULETTE SYSTEM.

Generate Android App

Online Meeting Instructions for Join.me

The Web Web page Links 16-3

SnagIt Add-Ins User Guide

Using The HomeVision Web Server

Managing Files. On a PC, after you find your file, right click it and selet Rename from the pop-up menu.

TUTORIAL 4 Building a Navigation Bar with Fireworks

Note: A WebFOCUS Developer Studio license is required for each developer.

Use the Package and Deployment Wizard to distribute your Visual Basic 6 programs

Making TIFF and EPS files from Drawing, Word Processing, PowerPoint and Graphing Programs

ATTENTION: End users should take note that Main Line Health has not verified within a Citrix

If you see "Skip installation of the current version and test the currently installed version of Java" then select that hyperlink.

Chapter 14: Links. Types of Links. 1 Chapter 14: Links

Android Programming Family Fun Day using AppInventor

A Practical Guide to Test Case Types in Java

Opening a Command Shell

THE GOVERNMENT OF THE REPUBLIC OF SINGAPORE MINISTRY OF MANPOWER WP ONLINE. Technical Guidelines

Basic Website Maintenance Tutorial*

How to Install Java onto your system

Welcome to Ipswitch Instant Messaging

Introduction to OpenOffice Writer 2.0 Jessica Kubik Information Technology Lab School of Information University of Texas at Austin Fall 2005

COMMON CUSTOMIZATIONS

X Series Application Note 43:

What you should know about: Windows 7. What s changed? Why does it matter to me? Do I have to upgrade? Tim Wakeling

How to Convert an Application into an Applet.

Graphical Environment Tool for Development versus Non Graphical Development Tool

Ubuntu To install the required card reader software:

How To Configure CU*BASE Encryption

Transcription:

Create a Java Applet Those of you who purchased my latest book, Learn to Program with Java, know that in the book, we create a Java program designed to calculate grades for the English, Math and Science departments of a university. At the completion of the book, we have a working Java program that uses a windows Interface to prompt for grade components, and then displays the results. In this article, I'm going to show you how to take the project and modify it so that it can be displayed in a web page. I think you'll find the process amazingly painless. What's an Applet? An applet is just a Java class that runs in a Web Browser such as Internet Explorer or Netscape. Creating an Applet is really easy, unfortunately, there's one problem. Neither Internet Explorer or Netscape support the latest and greatest from Java--namely its Swing Package, so if you intend to use Swing components in your Applet we need to do a little more work. But let's start with a simple Applet so that you can see what's going on. Let's write a simple applet from Scratch Here's the code for our first Applet which will display 'I love Java' as a message in a Web page import java.awt.*; import java.applet.*; public class Example14_1 extends Applet { public void paint(graphics g) { g.drawstring("i love Java",20,20); } } Let's take a closer look at the code and then we'll compile it and discuss how to 'run' it in a Web page. The first thing to note are the two import statements. We need to import 'awt' in order to produce the window within our browser. The second import statement is necessary because all Applets extend, or inherit from, the Java applet class. import java.awt.*; import java.applet.*; Because of that, the line of code defining the Applet class must use the keyword 'extends' as this one does here public class Example14_1 extends Applet { http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (1 of 11)3/28/2004 12:16:57 PM

The second thing to note is that Java Applets, unlike the Java Applications we followed in the book, may not have a main() method. A Java Applet, when it fires up in a Web Browser, automatically looks to execute three methods in this order. init() start() paint You can choose which of these to code. The init() method is executed when an Applet object is first instantiated. The start() method is executed after the init() method completes execution and every time the user of the browser returns to the HTML page on which the applet resides. The paint() method is called after the init method has completed and after the start() method has begun--most importantly, code in the paint() method is guaranteed to run each time the window needs to be re-drawn (i.e. after the browser has been minimized, covered, the HTML page has changed, etc). For our purposes, we coded the paint method, which uses a Graphics object (here defined as 'g')to do the drawing public void paint(graphics g) { The code in the paint() method is used to draw the window that will be displayed in the Web Browser. To do that we use the drawstring() method of the Graphics object, supplying the text that we wish to appear in the window and it's dimensions g.drawstring("i love Java",20,20); We need to write some HTML As I mentioned, Applet classes need to run within a Web Browser. Assuming you have now compiled the Java source file into a Bytecode file, we now need to create an HTML document which will create an instance of our Applet class when displayed in a Web Browser. (I don't intend to teach you HTML in this article--there are plenty of books and resources to do that.). Here's the HTML necessary to create an instance of our object and display its output in a Web Browser. I've saved the HTML as Example14_1.html http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (2 of 11)3/28/2004 12:16:57 PM

The HTML file contains two lines of code that will, in a bare-bones way, do the trick. HTML works primarily with tags, and the code that you see is an Applet tag to tell the Browser reading the HTML to create an instance of the Example14_1 class, within a window 200 pixels wide and 60 pixel high. We're now ready to load our Applet into a browser, but before we do that, I want to tell you about the Applet Viewer. Use the Applet Viewer to test our Applet Java includes, in its Java Developers Kit, a special interpreter called the Applet Viewer which can be used to test the Applets we write. To execute it, open up a Command Window and enter the following instructions to execute the HTML file we just wrote. http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (3 of 11)3/28/2004 12:16:57 PM

If we now press the ENTER key, we should see the Applet Viewer display window, and within it, the results of the execution of our Java applet The Applet Viewer can be shut down simply by clicking on its close button or Control Menu Icon. Display our Applet in a Web Browser To test our Applet in a Web Browser, we need to be sure that our Web Browser supports Java. Both Internet Explorer and Netscape have settings to turn Java 'on'---if you have doubts as to how to do that, check your Browser's help file. Assuming that your Browser has Java turned 'on', load up the HTML file we created into the Browser. Both Internet Explorer and Netscape permit you to display local HTML pages by selecting File-Open from the Menu Bar and selecting the HTML page. I'll do that here with Internet Explorer (just to show you that Microsoft has nothing against running a Java program!) http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (4 of 11)3/28/2004 12:16:57 PM

Here's our Applet running in Internet Explorer As you can see, the results are basically the same as those we found when running within the Applet Viewer---the difference is that the Web Browser is now acting as the container for our object, not the Applet Viewer. Now it's time to turn our attention to the Grades Calculation Project from my Java book. Convert the Grades Calculation Project into an Applet Let's take a look at the code we have right now in the Grades Calculation project. As you may recall, the final Grades project from the end of the book consists of a number of class modules. CalculateButtonListener DisplayGrade DrawGUI EnglishStudent GradesGUI MathStudent RadioButtonListener ResetButtonListener ScienceStudent Student http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (5 of 11)3/28/2004 12:16:57 PM

The good news is that in order to run our Java project from within a Web Page, we need to change just one of these classes---the GradesGUI class. Here's the code that currently resides there import javax.swing.*; import java.awt.*; import java.awt.event.*; class GradesGUI { public static void main(string args[]) { DrawGUI x = new DrawGUI(); x.addwindowlistener( new WindowAdapter() { public void windowclosing ( WindowEvent e ) { System.exit ( 0 ); } } // end of windowadpater ); // end of windowlistener } // end of main } // END OF CLASS and here's the modified code import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GradesApplet extends JApplet { public void init() { DrawGUI x = new DrawGUI(); x.addwindowlistener( new WindowAdapter() { public void windowclosing ( WindowEvent e ) { setvisible(false); } // end of windowclosing } // end of windowadpater ); // end of windowlistener } // end of void } // end of class The good news here is that most of the code from GradesGUI hasn t changed a bit--and neither have the other nine classes. Java truly lives up to its reputation of permitting us to build hardware and operating system independent class modules. In an ideal world we wouldn't have to change a thing, http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (6 of 11)3/28/2004 12:16:57 PM

but we do need to make a few changes. I've made three changes here. First, the Class definition now extends the JApplet class. JApplet is used in classes that contain Swing components---think of it as a Swing enabled version of the Applet class we used in the previous example. So that you don't confuse this code with the code you already have from the end of my Java book, let's name this class GradesApplet public class GradesApplet extends JApplet { The second change is to eliminate the main() method we had previously, and replace it with the init() method, which is its Applet counterpart. Remember, Applets may not have a main() method. We're using Init() here because this class, as did GradesGUI, really just instantiates other objects--it doesn't need to display anything. We want the DrawGUI object to be created when the Applet object is created--which is why we placed that code in the init() method. Those of you who are very observant probably notice that this is a new line of code setvisible(false); It's necessary to set make instance of the GradesApplet object, displayed in the Browser, invisible. In the previous version of the program we executed the exit() method of the System object--but that's not necessary here. Let's run the GradesCalculation Project in a Web Browser now That would be great, but unfortunately, our project uses Swing Components, and as I mentioned earlier, that will complicate things a little bit. First of all, current versions of Internet Explorer and Netscape don't know what to do with Swing Components. In order to run an Applet containing Swing Components in either of those two browsers, it's necessary to first go out to the Sun Website and download what is known as a Java Plug-in. You can read more about it here http://java.sun.com/docs/books/tutorial/uiswing/start/swingapplet.html and download it from here http://java.sun.com/products/plugin/ Once you have the plugin downloaded and installed (don't worry, it's painless), you might be inclined to code up an HTML file the way we did a few minutes ago and expect the Grades Calculation project to be displayed in your favorite Web Browser. We're close--very close to that---but the Plug-in will complicate matters. Instead of an HTML document http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (7 of 11)3/28/2004 12:16:57 PM

that looks like this <applet code="gradesapplet" width = 200 height=60> </applet> instead it needs to look like this <HTML> <BODY> <OBJECT classid="clsid:8ad9c840-044e-11d1-b3e9-00805f499d93" WIDTH = "1200" HEIGHT = "1200" codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#version=1,3,0,0"> <PARAM NAME = CODE VALUE = "GradesApplet.class" > <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3"> <PARAM NAME="scriptable" VALUE="false"> </OBJECT> </BODY> </HTML> Looks complicated, doesn t it? No need to concern yourself with it too much--just two lines of code require our attention. First, I've expanded the size of the window within the browser via this line of code WIDTH = "1200" HEIGHT = "1200" and it's this line of code that tells our browser that we wish to instantiate an instance of or GradesApplet class <PARAM NAME = CODE VALUE = "GradesApplet.class" > Having compiled GradesApplet into a ByteCode file (in a directory called \JFiles\GradesApplet) I can then open this page in a Browser http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (8 of 11)3/28/2004 12:16:57 PM

and magically, there's our Grades Calculation Project running in a browser. http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (9 of 11)3/28/2004 12:16:57 PM

Except for the fact that the window says 'Java Applet Window' at the bottom, we wouldn't even know that the project is running in a browser. Test the program--you should find that the functionality is identical to that of the other version---it should be, all we've done is change the Startup class to be an Applet. http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (10 of 11)3/28/2004 12:16:57 PM

Now just close the window--and the Applet stops. Summary I hope you ve enjoyed this article on creating Java Applets. I hope it's given you the confidence to create Applets of your own. Those of you who purchased my Java book, many thanks! http://www.johnsmiley.com/cis18.notfree/smiley031/smiley031.htm (11 of 11)3/28/2004 12:16:57 PM