Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
JavaScript – Comprehensive
Tutorial 12
Tutorial 12
Working with Java Applets and Embedded
Data
At a Glance
Instructor’s Notes
Chapter Overview
Chapter Outline
System Installation and Requirements
Lecture Notes
Section A
ODBC
SQL
LiveWire Database Object
Execute Method
The Cursor Object
Transaction Processing
Section B
ADO
The ADO Connection Object
The ADO RecordSet Object
Solutions
Solutions to Questions
Solutions to Exercises
12-1
JavaScript – Comprehensive
Tutorial 12
Instructor’s Notes
CHAPTER OVERVIEW
Using Java Applets and Embedded Data technologies (plug-ins), such as ActiveX, you can
bring new processing capabilities to your Web pages: capabilities not normally found within
the bounds of the DHTML standards. These techniques can expand the capability of the
browser in unique ways, but may not be fully compatible across platforms.
CHAPTER OUTLINE
Lecture Topics
Page #
Teaching Suggestions in this Manual
Applets and Embedded Data
654
Introduction to Java
Classes
656
658
Methods
Compiling a Java Program
Creating an Applet
Java Variables and Data Types
Adding an Applet to an HTML
Document
Controlling Java Applets with
JavaScript
Java Packages and LiveConnect
659
661
662
665
669
See Lecture Notes, "Applets and
Embedded Data"
See Lecture Notes, "Java"
See Lecture Notes, “Classes and
Methods”
See Lecture Notes, "Classes and Methods”
See Lecture Notes, ”Compiling”
See Lecture Notes, "The Cursor Object"
See Lecture Notes, "Java"
See Lecture Notes, "Java Applets"
Data Conversion Between Java and
JavaScript
Controlling JavaScript with Java
685
Importing the JSObject and
JSException Classes
Using the JSObject Class Methods
The MAYSCRIPT Attribute
Directly Accessing Java Classes from
JavaScript
Embedded Data
687
Plug-ins
ActiveX Controls
695
703
672
683
686
688
692
693
695
See Lecture Notes, "Java Applets and
JavaScript"
See Lecture Notes, "Netscape's Support
for Java"
See Lecture Notes, "Java Applets and
JavaScript"
See Lecture Notes, "Mixing JavaScript
and Java"
See Lecture Notes
See Lecture Notes
See Lecture Notes
See Lecture Notes, "Mixing JavaScript
and Java"
See Lecture Notes, "Plug-ins" and
"ActiveX Scripting"
See Lecture Notes, "Plug-ins"
See Lecture Notes, "ActiveX Scripting"
SYSTEM INSTALLATION AND REQUIREMENTS
Java Development Kit (JDK)
The latest version of the Java Development Kit can be downloaded free of charge from Sun's
12-1
JavaScript – Comprehensive
Java Technology Web site:
http://www.javasoft.com
Tutorial 12
The exercises in the text were created using the Java 2 SE language standard. If Java 1 is
used, there may be some variation in functionality. The latest Java 2 SE version at the time
of this printing is version 1.3. This version is recommended and can be found at:
http://www.javasoft.com/j2se/1.3/download-windows.html.
To install this version, follow the latest directions, available at:
http://www.javasoft.com/j2se/1.3/install-windows.html#install
12-1
JavaScript – Comprehensive
Tutorial 12
LECTURE NOTES
Applets and Embedded Data
Extending your Web application using Java and Plug-in technologies can really make a
difference in the presentation and processing capabilities. However, it will also impact the
compatibility of your apps with older browsers and sometimes with clients accessing the
Internet through slower connections. The need to download extra information in the form of
Java code or Plug-in executables may be inconvenient to the casual surfer and should be
used sparingly if you are unsure of your Web site's audience.
Java
There are many useful tutorials and reference sites available for the many Java flavors used
by Web programmers. The most definitive is Sun's own Java Web site, JavaSoft.com. You
will find information about new releases, tutorials on using the Java language, and
information on the history of the language.
Java is a platform-independent programming language. The intention was to create a
robust, object-oriented programming language that would allow developers to build programs
that would run consistently on any given operating system on any given machine. Java
syntax is loosely based on the syntax for the compiled language, C++, and is itself used as a
basis for the JavaScript language explored in this book.
The strategy employed by Java's creators for achieving platform independence is to first
create a standard machine-within-the-machine, or Virtual Machine, that would be ported to
any desired platform and would be used to execute the Java program directives. The task of
the Java Virtual Machine (JVM) is to abstract the functions that are normally handled in
vendor/platform specific ways, like printing, file access, etc. This means that the Java
programmer has a single interface to program that will automatically be translated by the
JVM into the operating system specific directives required to enact the commands.
Classes and Methods
The object-oriented nature of Java is lightly carried into the JavaScript programming
language. Those OOP concepts you were exposed to in earlier tutorials will typically apply to
the design of a Java program. The language however, requires more specific syntax be
followed to implement these entities.
Compiling
Compilation is a concept not yet covered in this book, since it is not typically necessary to
compile programs used on the web. The term "compiling" typically refers to the process of
translating lines of program code into a set of machine language instructions that the
microprocessor hardware can support. This machine language, also known as assembly
language, differs from chip manufacturer to chip manufacturer. In the case of Java, the
compilation of Java code results in a file containing 'Bytecode' rather than Assembly code.
Bytecode is a low-level language with a similar purpose-- it is the instruction set that can be
interpreted by Java Virtual Machine. The VM is written to hide the differences between
computer operating systems and microprocessor chips.
To compile a program requires a compiler. The javac.exe is the Java compiler used to
compile your .java code files into usable Bytecode .class files.
Java Applets
The Java language embraces two types of executable entity: an application and an applet.
An application written in Java will produce a .exe or equivalent file that can be run as a
stand-alone on a given computer. An applet, however, can only be run through the use of a
compatible Web browser. Applets are designed to take advantage of the environment
provided by a browser window to perform it's programmed tasks.
12-1
JavaScript – Comprehensive
Tutorial 12
Java Applets and JavaScript
Since Java Applets always exist within the boundaries of a Web browser, they can be
referenced by JavaScript calls contained in the same pages as the Applet references. All of
the Applets installed within a specific Web page can be referenced in JavaScript through the
applets[] array of the Document object. JavaScript calls may be made to the Java Applet's
methods once the Applet object can be referenced.
Passing Data between JavaScript and Java
When accessing methods written in one language from code written in another, expect
problems. Java and JavaScript do not support the same data types, therefore, data must be
translated appropriately in order for it to be used by the receiving program. Since
JavaScript is a loosely typed language and Java is a strongly typed language, it may be
difficult to identify the actual type used by the JavaScript program to represent any given
piece of data.
This may be particularly true when dealing with numbers. Take the value '52'. It could be
easily seen as a numeric data type, but it may be stored as a string composed of the two
characters '5' and '2'.
Netscape's Support for Java
Netscape has chosen to make Web pages extendible through advanced support for the mixing
of Java and JavaScript. LiveConnect technology allows the Java programmer to control the
execution of the JavaScript code by supplying two customized Java Packages, JSObject and
JSException.
For more info on the LiveConnect technology, see the Netscape DevEdge Web site at:
http://developer.netscape.com/docs/manuals/js/client/jsguide/lc.htm
NOTE: To enable the support for LiveConnect functionality in your Java Applets,
you must include the path to the java40.jar file in your CLASSPATH environment
variable.
Mixing JavaScript and Java
The Packages object in JavaScript provides direct access to Java objects and methods from
your JavaScript code. As noted before, there should be care taken to ensure that the data
types passed as arguments to Java methods are those appropriate to the method.
Plug-ins
To allow further extension of the browser's capabilities, Netscape's browsers support the idea
of a Plug-in module that will allow the browser to display a customized object within the
mixed HTML window. Common plug-ins include LiveAudio for streaming audio content and
Shockwave for streaming animation and sound.
Check-out the latest free, downloadable plug-ins on Netscape's Web site at:
http://home.netscape.com/plugins/
ActiveX Scripting
ActiveX Scripting is Microsoft's answer to Plug-in and LiveConnect capability provided by
Netscape. ActiveX Controls are programmatic objects that can be reused in many of
Microsoft's development environments, including JavaScript and VBScript environments
supported by IE.
12-1
JavaScript – Comprehensive
Tutorial 12
Solutions to Questions
SECTION A
1. c. A Java program that runs from within a Web page is called a(n) applet.
2. b. Encapsulation means that all code and required data are self-contained within the
object itself.
3. a. A(n) bounding box is the rectangular area on a Web page in which an applet executes.
4. b. Object-oriented programming refers to the creation of reusable software objects that can
be easily incorporated into another program.
5. d. Java code runs on any platform because it is architecturally neutral.
6. c. The Java Virtual Machine is the language interpreter for the Java programming
language.
7. a. The Java Development Kit is the original development environment for creating Java
programs.
8. c. A method is a structure similar to a function, which contains a class's statements and
procedures.
9. a. What is the correct syntax of the class header for a Java file named PayrollApplet?
public class PayrollApplet {
10. d. Collections of related classes are called packages or class libraries.
11. c. The public keyword makes a method available outside of its class.
12. b. Which Java methods are similar to JavaScript's write() and writeln() methods? print()
and println()
13. b. Which program compiles Java code into a file with an extension of .class? javac
14. a. The compiled Java code executed by the Java interpreter is called bytecode.
15. d. The method that acts as the entry point for a standalone Java program is the main()
method.
16. a. Which of the following is NOT one of the four applet methods that run automatically at
different points in an applet's execution? load()
17. b. Which of the following is the correct class header for an applet saved in a file named
AccountingApplet.java? public class AccountingApplet extends Applet {
18. a. The paint() method displays the visual components of an applet in a browser window
and runs automatically whenever the browser window is minimized, maximized, or resized.
19. b. Which of the following statements declares a string variable in Java? String
textString = new String("This is my text string");
12-1
JavaScript – Comprehensive
Tutorial 12
20. d. For an instance variable to be available outside a class, it must have an access modifier
of public.
21. a. The random() method of the Math class returns a number between 0.0 and 1.0.
22. d. You add an applet to an HTML document using the <APPLET> tag.
SECTION B
. d. Java packages and their directory structure are contained in a compressed ZIP file
named _____. classes.zip
Note: To present information on the most current version of the JDK, the sentence in the
text relevant to this question was revised to read "Java packages and their class structures
are contained in compressed JAR files located within the JDK directory." The newest
version of the JDK no longer uses the classes.zip file.
2. a. The LiveConnect packages for Navigator 4 are contained in the java40.jar compressed
file.
3. c. The CLASSPATH environment variable tells the Java VM and JDK applications in the
/bin directory where to search for classes required by Java applications.
4. a. The JSObject class contains methods to allow Java and JavaScript to interact, and acts
as a wrapper for JavaScript objects.
5. a. Which of the following statements imports the LiveConnect packages into a Java
program? netscape.javascript.*;
6. d. Which of the following is the correct syntax for obtaining a handle to a window?
JSObject windowVar = JSObject.getWindow(this);
*7. a. Which of the following returns a reference to a window's Document object, assuming
that you have already declared a handle named windowVar? JSObject windowVar =
(JSObject) jsWindow.getMember("document");
Note: The stem for this question should read "Which of the following returns a reference to a
window's Document object, assuming that you have already declared a handle named
JSwindow?" Then, alternative a. is the most correct answer, and it should read JSObject
JSwindow = (JSObject) JSwindow.getMember("document");
8. d. How do you assign the value of a JavaScript form element to a Java string variable,
assuming that you have already created a reference to a text box named textField? String
javaStringVar = (String) textField.getMember("value");
9. c. What is the correct syntax for executing a JavaScript alert dialog box from a Java
program, assuming that you have already declared a handle named windowVar?
windowVar.eval("alert('Text String');");
10. b. Which attribute gives Java programs access to an HTML document's elements and
JavaScript? MAYSCRIPT
11. a. Which of the following statements gives JavaScript programs in Navigator access to
the round() method of Java's java.lang.Math class? Packages.java.lang.Math.round();
12-1
JavaScript – Comprehensive
Tutorial 12
12. a. What is the name of the plugin from NCompass that allows Navigator to use ActiveX
controls? ScriptActive
Note: The ScriptActive plugin from NCompass is no longer available. Therefore the relevant
information was deleted from the text.
13. d. Plugins are software components created by third-party developers that allow the
display and execution of embedded data inside a Navigator window.
14. d. Embedded data is associated with a particular plugin by its MIME type or file
extension.
15. d. Embedded data is added to a Web page using the <EMBED> tag.
16. c. You refer to embedded data in JavaScript using its NAME attribute or by referring to
its element number in the embeds[] array.
17. a. On which of the following platforms can you use ActiveX controls? Windows
18. b. ActiveX controls are added to a Web page using the <OBJECT> tag.
19. a. You refer to an embedded ActiveX control in JavaScript using its ID attribute.
20. d. The unique identifer required by the system to locate a specific ActiveX control is
called a CLASSID.
21. b. Values are passed to an ActiveX control through <PARAM> tags.
22. c. Microsoft's free program that helps add ActiveX controls to an HTML document is
called ActiveX Control Pad.
12-1
JavaScript – Comprehensive
Tutorial 12
Solutions to Exercises
Section A
Exercise 1
JAVA file PersonalInfo.java:
public class PersonalInfo {
public static void main (String args[]) {
System.out.print("Name: ");
System.out.println("Don Gosselin");
System.out.print("Address: ");
System.out.println("49 Cranberry Meadow Road");
System.out.print("City, State, ZIP: ");
System.out.println("Spencer, MA 01562");
System.out.print("Date of Birth: ");
System.out.println("1/27/65");
}
}
Exercise 2
JAVA file Paycheck.java:
public class Paycheck{
public static void main (String args[]) {
int hourlyPay = 25;
int hoursWorked = 40;
System.out.println("WEEKLY PAYCHECK");
System.out.println("All numbers are rounded to the nearest dollar.");
System.out.println("**********************************************");
System.out.println("Number of hours: 40");
System.out.println("Hourly wage: $25");
int grossPay = hourlyPay * hoursWorked;
System.out.print("Gross weekly pay: $");
System.out.println(grossPay);
double dTaxes = grossPay * .15;
long taxes = (long) dTaxes;
long netPay = grossPay - taxes;
System.out.println("15% tax withholding: $" + taxes);
System.out.print("Net weekly pay (gross pay minus taxes): $");
System.out.println(netPay);
}
}
12-1
JavaScript – Comprehensive
Exercise 3
Tutorial 12
HTML file RoomSize.html:
<HTML>
<HEAD>
<TITLE>Room Size</TITLE>
</HEAD>
<BODY>
<APPLET CODE="RoomSize.class" NAME="RoomSize" WIDTH=100 HEIGHT=50>
</APPLET>
<P>
<SCRIPT LANGUAGE="JavaScript1.2">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
document.write("<H3>The length of the room is " +
document.RoomSize.length);
document.write("<H3>The width of the room is " +
document.RoomSize.width);
document.write("<H3>The room is " + document.RoomSize.floorSpace + "
square feet");
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</BODY>
</HTML>
JAVA file RoomSize.java:
import java.applet.*;
import java.awt.*;
public class RoomSize extends Applet {
public int length = 10;
public int width = 12;
public int floorSpace;
public void start() {
floorSpace = length * width;
repaint();
}
public void paint (Graphics g) {
g.drawString("Room Size", 25, 25);
}
}
Exercise 4
HTML file FavoriteMovies.html:
<HTML>
<HEAD>
<TITLE>Favorite Movies</TITLE>
<HEAD>
<BODY>
<APPLET CODE="FavoriteMovies.class" NAME="FavoriteMovies" WIDTH=400
HEIGHT=100>
</APPLET>
<P>
<FORM>
12-1
JavaScript – Comprehensive
<INPUT TYPE="button" VALUE=" Favorite Comedies "
onClick="document.FavoriteMovies.comedy();"><P>
<INPUT TYPE="button" VALUE=" Favorite Dramas "
onClick="document.FavoriteMovies.drama();"><P>
<INPUT TYPE="button" VALUE=" Favorite Movie "
onClick="document.FavoriteMovies.favoriteMovie();"><BR>
</FORM>
</BODY>
</HTML>
Tutorial 12
JAVA file FavoriteMovies.java:
import java.applet.*;
import java.awt.*;
public class FavoriteMovies extends Applet {
public String favoriteMovie = new String();
public String firstFavoriteComedy = new String();
public String secondFavoriteComedy = new String();
public String thirdFavoriteComedy = new String();
public String firstFavoriteDrama = new String();
public String secondFavoriteDrama = new String();
public String thirdFavoriteDrama = new String();
public int printWhat;
public void start() {
repaint();
}
public void paint (Graphics g) {
if (printWhat == 1) {
g.drawString("My favorite comedies are:", 25, 25);
g.drawString(firstFavoriteComedy, 25, 40);
g.drawString(secondFavoriteComedy, 25, 55);
g.drawString(thirdFavoriteComedy, 25, 70);
}
else if (printWhat == 2) {
g.drawString("My favorite dramas are:", 25, 25);
g.drawString(firstFavoriteDrama, 25, 40);
g.drawString(secondFavoriteDrama, 25, 55);
g.drawString(thirdFavoriteDrama, 25, 70);
}
else if (printWhat == 3) {
g.drawString("My absolute favorite movie is:", 25, 25);
g.drawString(favoriteMovie, 25, 40);
}
else
g.drawString("Click a button to see my favorite movies.", 25,
25);
}
public void comedy() {
firstFavoriteComedy = "Austin Powers";
secondFavoriteComedy = "The Nutty Professor";
thirdFavoriteComedy = "Ghost Busters";
printWhat = 1;
repaint();
}
public void drama() {
12-1
JavaScript – Comprehensive
firstFavoriteDrama = "Gone With The Wind";
secondFavoriteDrama = "Casablanca";
thirdFavoriteDrama = "Forrest Gump";
printWhat = 2;
repaint();
}
public void favoriteMovie() {
favoriteMovie = "Lawrence of Arabia";
printWhat = 3;
repaint();
}
}
Exercise 5
HTML file JobInfo.html:
<HTML>
<HEAD>
<TITLE>Job Info</TITLE>
</HEAD>
<BODY>
<H2>Job Info</H2>
<APPLET CODE="JobInfo.class" NAME="EmployeeInfo" WIDTH=400
HEIGHT=100>
</APPLET>
<P>
<FORM NAME="Info">
Name: <INPUT TYPE="text" NAME="name"><BR>
Employer: <INPUT TYPE="text" NAME="employer"><BR>
Job Title: <INPUT TYPE="text" NAME="title"><BR>
Starting Salary: <INPUT TYPE="text" NAME="salary"><BR>
Age: <INPUT TYPE="text" NAME="age"><P>
<INPUT TYPE="button" VALUE=" Display in Bounding Box "
onClick="document.EmployeeInfo.showInfo(
document.Info.name.value,
document.Info.employer.value,
document.Info.title.value,
document.Info.salary.value,
document.Info.age.value);">
</FORM>
</BODY>
</HTML>
JAVA file JobInfo.java:
import java.applet.*;
import java.awt.*;
public class JobInfo extends Applet {
public String employee = new String("");
public String employer = new String("");
public String jobTitle = new String("");
long startingSalary;
12-1
Tutorial 12
JavaScript – Comprehensive
Tutorial 12
int age;
public void start() {
repaint();
}
public void paint (Graphics g) {
g.drawString("Employee: " + employee , 25, 25);
g.drawString("Employer: " + employer, 25, 40);
g.drawString("Job Title: " + jobTitle, 25, 55);
g.drawString("Starting Salary: " + startingSalary, 25, 70);
g.drawString("Age: " + age, 25, 85);
}
public void showInfo(String name, String emp, String position, long wage, int
howOld) {
employee = name;
employer = emp;
jobTitle = position;
startingSalary = wage;
age = howOld;
repaint();
}
}
Exercise 6
HTML file ConvertTemperature.html:
<TITLE>Convert Temperature</TITLE>
<SCRIPT LANGUAGE="JavaScript1.2">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function checkCelcius() {
if (document.Converter.fahrenheit.value == "")
alert("You must enter a temperature in the Fahrenheit box!");
else
document.ConvertTemperature.convertToCelcius(document.Converter.fahren
heit.value);
}
function checkFahrenheit() {
if (document.Converter.celcius.value == "")
alert("You must enter a temperature in the Celcius box!");
else
document.ConvertTemperature.convertToFahrenheit(document.Converter.cel
cius.value);
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</HEAD>
<BODY>
<H1>Convert Temperature</H1>
<APPLET CODE="ConvertTemperature.class" NAME="ConvertTemperature"
WIDTH=400 HEIGHT=50>
</APPLET>
<P>
<FORM NAME="Converter">
<B>Enter the temperature in Fahrenheit</B><BR>
12-1
JavaScript – Comprehensive
<INPUT TYPE="text" NAME="fahrenheit">
<INPUT TYPE="button" VALUE=" Convert to Celcius "
onClick="checkCelcius();"><P>
<B>Enter the temperature in Celcius</B><BR>
<INPUT TYPE="text" NAME="celcius">
<INPUT TYPE="button" VALUE=" Convert to Fahrenheit "
onClick="checkFahrenheit();"><P>
</FORM>
</BODY>
</HTML>
Tutorial 12
JAVA file ConvertTemperature.html:
import java.applet.*;
import java.awt.*;
public class ConvertTemperature extends Applet {
public String displayText = new String();
public void start() {
displayText = "Temperature Converter";
repaint();
}
public void paint (Graphics g) {
g.drawString(displayText, 25, 25);
}
public void convertToCelcius(float temperature) {
long tempInCelcius = Math.round((temperature - 32) * .55);
displayText = "The temperature you entered as Fahrenheit is equal to
" + tempInCelcius + " in Celcius";
repaint();
}
public void convertToFahrenheit(float temperature) {
long tempInFahrenheit = Math.round((temperature * 1.8) + 32);
displayText = "The temperature you entered as Celcius is equal to " +
tempInFahrenheit + " in Fahrenheit";
repaint();
}
Section B
Exercise 1
HTML file WorkHistory.html:
<HTML>
<HEAD>
<TITLE>Work History</TITLE>
</HEAD>
<BODY>
<APPLET CODE="WorkHistory.class" NAME="WorkHistory" WIDTH=400
HEIGHT=50>
</APPLET>
<P>
<FORM NAME="Employment">
<B>First Employer</B><BR>
Name: <INPUT TYPE="text" NAME="employer1"><BR>
12-1
JavaScript – Comprehensive
Salary: <INPUT TYPE="text" NAME="salary1"><BR>
Years Employed: <INPUT TYPE="text" NAME="years1"><BR>
<B>Second Employer</B><BR>
Name: <INPUT TYPE="text" NAME="employer2"><BR>
Salary: <INPUT TYPE="text" NAME="salary2"><BR>
Years Employed: <INPUT TYPE="text" NAME="years2"><BR>
<B>Third Employer</B><BR>
Name: <INPUT TYPE="text" NAME="employer3"><BR>
Salary: <INPUT TYPE="text" NAME="salary3"><BR>
Years Employed: <INPUT TYPE="text" NAME="years3"><P>
<INPUT TYPE="button" VALUE=" Highest Salary "
onClick="document.WorkHistory.highestSalary(
document.Employment.employer1.value,
parseInt(document.Employment.salary1.value),
document.Employment.employer2.value,
parseInt(document.Employment.salary2.value),
document.Employment.employer3.value,
parseInt(document.Employment.salary3.value))">
<INPUT TYPE="button" VALUE=" Lowest Salary "
onClick="document.WorkHistory.lowestSalary(
document.Employment.employer1.value,
parseInt(document.Employment.salary1.value),
document.Employment.employer2.value,
parseInt(document.Employment.salary2.value),
document.Employment.employer3.value,
parseInt(document.Employment.salary3.value))">
<INPUT TYPE="button" VALUE=" Longest Employment "
onClick="document.WorkHistory.longestEmployment(
document.Employment.employer1.value,
parseInt(document.Employment.years1.value),
document.Employment.employer2.value,
parseInt(document.Employment.years2.value),
document.Employment.employer3.value,
parseInt(document.Employment.years3.value))">
<INPUT TYPE="button" VALUE=" Shortest Employment "
onClick="document.WorkHistory.shortestEmployment(
document.Employment.employer1.value,
parseInt(document.Employment.years1.value),
document.Employment.employer2.value,
parseInt(document.Employment.years2.value),
document.Employment.employer3.value,
parseInt(document.Employment.years3.value))">
</FORM>
</BODY>
</HTML>
JAVA file WorkHistory.java:
import java.applet.*;
import java.awt.*;
public class WorkHistory extends Applet {
public String displayText = new String();
public void start() {
displayText = "Work History";
repaint();
}
12-1
Tutorial 12
JavaScript – Comprehensive
Tutorial 12
public void paint (Graphics g) {
g.drawString(displayText, 25, 25);
}
public void highestSalary(String employer1, int salary1,
String employer2, int salary2,
String employer3, int salary3) {
int firstCalc = Math.max(salary1, salary2);
int secondCalc = Math.max(firstCalc, salary3);
if (secondCalc == salary1)
displayText = "The highest salary was earned at " +
employer1;
else if (secondCalc == salary2)
displayText = "The highest salary was earned at " +
employer2;
else if (secondCalc == salary3)
displayText = "The highest salary was earned at " +
employer3;
repaint();
}
public void lowestSalary(String employer1, int salary1,
String employer2, int salary2,
String employer3, int salary3) {
int firstCalc = Math.min(salary1, salary2);
int secondCalc = Math.min(firstCalc, salary3);
if (secondCalc == salary1)
displayText = "The lowest salary was earned at " +
employer1;
else if (secondCalc == salary2)
displayText = "The lowest salary was earned at " +
employer2;
else if (secondCalc == salary3)
displayText = "The lowest salary was earned at " +
employer3;
repaint();
}
public void longestEmployment(String employer1, int years1,
String employer2, int years2,
String employer3, int years3) {
int firstCalc = Math.max(years1, years2);
int secondCalc = Math.max(firstCalc, years3);
if (secondCalc == years1)
displayText = "The longest period of employment was with " +
employer1;
else if (secondCalc == years2)
displayText = "The longest period of employment was with " +
employer2;
else if (secondCalc == years3)
displayText = "The longest period of employment was with " +
employer3;
repaint();
}
public void shortestEmployment(String employer1, int years1,
String employer2, int years2,
String employer3, int years3) {
int firstCalc = Math.min(years1, years2);
int secondCalc = Math.min(firstCalc, years3);
12-1
JavaScript – Comprehensive
Tutorial 12
if (secondCalc == years1)
displayText = "The shortest period of employment was with "
+ employer1;
else if (secondCalc == years2)
displayText = "The shortest period of employment was with "
+ employer2;
else if (secondCalc == years3)
displayText = "The shortest period of employment was with "
+ employer3;
repaint();
}
}
Exercise 2
HTML file Calculator_IE.html:
<HTML>
<HEAD>
<TITLE>Calculator</TITLE>
<SCRIPT LANGUAGE="JavaScript1.2">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
var inputString = "";
function updateApplet(calcValue) {
inputString += calcValue;
document.Calculate.updateDisplay(inputString);
}
function performCalc() {
var calcValue = eval(inputString);
inputString = calcValue;
document.Calculate.updateDisplay(inputString);
}
function clearCalculator() {
inputString = "";
document.Calculate.updateDisplay(inputString);
}
function exp() {
if (inputString == "")
alert("You must enter a value!");
else {
calcNum = eval(inputString);
inputString = document.Calculate.calcExp(calcNum);
document.Calculate.updateDisplay(inputString);
}
}
function squareRoot() {
if (inputString == "")
alert("You must enter a value!");
else {
calcNum = eval(inputString);
inputString = document.Calculate.calcSqrt(calcNum);
document.Calculate.updateDisplay(inputString);
}
}
function sine() {
12-1
JavaScript – Comprehensive
Tutorial 12
if (inputString == "")
alert("You must enter a value!");
else {
calcNum = eval(inputString);
inputString = document.Calculate.calcSin(calcNum);
document.Calculate.updateDisplay(inputString);
}
}
function cosine() {
if (inputString == "")
alert("You must enter a value!");
else {
calcNum = eval(inputString);
inputString = document.Calculate.calcCosin(calcNum);
document.Calculate.updateDisplay(inputString);
}
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<APPLET CODE="Calculator_IE.class" NAME="Calculate" HEIGHT=20
WIDTH=175></APPLET>
<FORM NAME="Calculator">
<INPUT TYPE="button" NAME="plus" VALUE=" + "
onClick="updateApplet('+');">
<INPUT TYPE="button" NAME="minus" VALUE=" - " onClick="updateApplet('');">
<INPUT TYPE="button" NAME="times" VALUE=" x "
onClick="updateApplet('*');">
<INPUT TYPE="button" NAME="div" VALUE=" / " onClick="updateApplet('/');">
<INPUT TYPE="button" NAME="mod" VALUE=" MOD "
onClick="updateApplet('%');">
<BR>
<INPUT TYPE="button" NAME="sin" VALUE="EXP" onClick="exp();">
<INPUT TYPE="button" NAME="sqrt" VALUE="SQRT" onClick="squareRoot();">
<INPUT TYPE="button" NAME="sin" VALUE="SIN" onClick="sine();">
<INPUT TYPE="button" NAME="sin" VALUE="COS" onClick="cosine();">
<BR>
<INPUT TYPE="button" NAME="zero" VALUE=" 0 "
onClick="updateApplet('0');">
<INPUT TYPE="button" NAME="one" VALUE=" 1 "
onClick="updateApplet('1');">
<INPUT TYPE="button" NAME="two" VALUE=" 2 "
onClick="updateApplet('2');">
<INPUT TYPE="button" NAME="three" VALUE=" 3 "
onClick="updateApplet('3');">
<INPUT TYPE="button" NAME="four" VALUE=" 4 "
onClick="updateApplet('4');">
<BR>
<INPUT TYPE="button" NAME="five" VALUE=" 5 " onClick="updateApplet('5');">
<INPUT TYPE="button" NAME="six" VALUE=" 6 " onClick="updateApplet('6');">
<INPUT TYPE="button" NAME="seven" VALUE=" 7 "
onClick="updateApplet('7');">
<INPUT TYPE="button" NAME="eight" VALUE=" 8 "
12-1
JavaScript – Comprehensive
onClick="updateApplet('8');">
<INPUT TYPE="button" NAME="nine"
onClick="updateApplet('9');">
<BR>
<INPUT TYPE="button" NAME="point"
<INPUT TYPE="button" NAME="clear"
onClick="clearCalculator();">
<INPUT TYPE="button" NAME="Calc"
</FORM>
</CENTER>
</BODY>
</HTML>
Tutorial 12
VALUE=" 9 "
VALUE=" . " onClick="updateApplet('.');">
VALUE=" Clear "
VALUE=" = " onClick="performCalc();">
HTML file Calculator_Navigator.html:
<HTML>
<HEAD>
<TITLE>Calculator</TITLE>
<SCRIPT LANGUAGE="JavaScript1.2">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function exp() {
if (document.Calculator.Input.value == "")
alert("You must enter a value!");
else {
calcNum = eval(document.Calculator.Input.value);
var expValue = Packages.java.lang.Math.exp(calcNum);
document.Calculator.Input.value = expValue;
}
}
function squareRoot() {
if (document.Calculator.Input.value == "")
alert("You must enter a value!");
else {
calcNum = eval(document.Calculator.Input.value);
var sqrtValue = Packages.java.lang.Math.sqrt(calcNum);
document.Calculator.Input.value = sqrtValue;
}
}
function sine() {
if (document.Calculator.Input.value == "")
alert("You must enter a value!");
else {
calcNum = eval(document.Calculator.Input.value);
var sinValue = Packages.java.lang.Math.sin(calcNum);
document.Calculator.Input.value = sinValue;
}
}
function cosine() {
if (document.Calculator.Input.value == "")
alert("You must enter a value!");
else {
calcNum = eval(document.Calculator.Input.value);
var cosValue = Packages.java.lang.Math.cos(calcNum);
document.Calculator.Input.value = cosValue;
}
}
12-1
JavaScript – Comprehensive
Tutorial 12
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<FORM NAME="Calculator">
<INPUT TYPE="text" NAME="Input" Size="22">
<BR>
<INPUT TYPE="button" NAME="plus" VALUE=" + "
onClick="document.Calculator.Input.value+='+'">
<INPUT TYPE="button" NAME="minus" VALUE=" - "
onClick="document.Calculator.Input.value+='-'">
<INPUT TYPE="button" NAME="times" VALUE=" x "
onClick="document.Calculator.Input.value+='*'">
<INPUT TYPE="button" NAME="div" VALUE=" / "
onClick="document.Calculator.Input.value+='/'">
<INPUT TYPE="button" NAME="mod" VALUE=" MOD "
onClick="document.Calculator.Input.value+='%'">
<BR>
<INPUT TYPE="button" NAME="sin" VALUE="EXP" onClick="exp()">
<INPUT TYPE="button" NAME="sqrt" VALUE="SQRT" onClick="squareRoot()">
<INPUT TYPE="button" NAME="sin" VALUE="SIN" onClick="sine()">
<INPUT TYPE="button" NAME="sin" VALUE="COS" onClick="cosine()">
<BR>
<INPUT TYPE="button" NAME="zero" VALUE=" 0 "
onClick="document.Calculator.Input.value+='0'">
<INPUT TYPE="button" NAME="one" VALUE=" 1 "
onClick="document.Calculator.Input.value+='1'">
<INPUT TYPE="button" NAME="two" VALUE=" 2 "
onClick="document.Calculator.Input.value+='2'">
<INPUT TYPE="button" NAME="three" VALUE=" 3 "
onClick="document.Calculator.Input.value+='3'">
<INPUT TYPE="button" NAME="four" VALUE=" 4 "
onClick="document.Calculator.Input.value+='4'">
<BR>
<INPUT TYPE="button" NAME="five" VALUE=" 5 "
onClick="document.Calculator.Input.value+='5'">
<INPUT TYPE="button" NAME="six" VALUE=" 6 "
onClick="document.Calculator.Input.value+='6'">
<INPUT TYPE="button" NAME="seven" VALUE=" 7 "
onClick="document.Calculator.Input.value+='7'">
<INPUT TYPE="button" NAME="eight" VALUE=" 8 "
onClick="document.Calculator.Input.value+='8'">
<INPUT TYPE="button" NAME="nine" VALUE=" 9 "
onClick="document.Calculator.Input.value+='9'">
<BR>
<INPUT TYPE="button" NAME="point" VALUE=" . "
onClick="document.Calculator.Input.value+='.'">
<INPUT TYPE="button" NAME="clear" VALUE=" Clear "
onClick="document.Calculator.Input.value=''">
<INPUT TYPE="button" NAME="Calc" VALUE=" = "
onClick="Input.value=eval(document.Calculator.Input.value);">
</FORM>
</CENTER>
</BODY>
</HTML>
12-1
JavaScript – Comprehensive
Tutorial 12
JAVA file Calculator_IE.java:
import java.applet.*;
import java.awt.*;
public class Calculator_IE extends Applet {
public String displayText = new String();
public void paint (Graphics g) {
g.drawString(displayText, 10, 15);
}
public void updateDisplay(String calculation) {
displayText = calculation;
repaint();
}
public double calcExp(double calcNum) {
double retNum = Math.exp(calcNum);
return retNum;
}
public double calcSqrt(double calcNum) {
double retNum = Math.sqrt(calcNum);
return retNum;
}
public double calcSin(double calcNum) {
double retNum = Math.sin(calcNum);
return retNum;
}
public double calcCosin(double calcNum) {
double retNum = Math.cos(calcNum);
return retNum;
}
}
12-1