You are on page 1of 28

* The fundamental client side programming language for the web.

* "Java is just a small, simple, safe, objectoriented, interpreted or dynamically optimized, bytecoded, architecture-neutral, garbage-collected, multithreaded programming language with a strongly typed exception-handling mechanism for writing distributed dynamically extensible program." ---- Bill Joy, cofounder of SUN Microsystems.

History

* It was originally called Oak, developed by SUN Microsystems, in a project called FirstPerson for smart appliances, such as set-top-box (interactive TV) 1992, lead by James Gosling. * It adopted C++ syntax but get rid of pointer, memory management, and multiple inheritance, which are main causes of programming errors.

* It failed to be adopted by Timer Warner in Spring 93's ITV trial. * 1993 Marc Andreesen developed Mosaic Web Browser, started the web revolution. * Oak found its reason for existence. A Web browser called WebRunner was developed for demonstration. * January 1995, Sun adopted Java name due to trademark issue. * Marc Andreesen saw the demo and license it for use in its browser. * Nov. 1995, 1st Beta release with developer kit and source code.

What is Java Applet

* Java is a general purpose programming language.

* A Java program is created as a text file with .java extension. * It is compiled into one or more files of bytecodes with .class extension. * Bytecodes are a set of instructions similar to machine code of a specific machine but it can be run on any machine that has a Java Virtual Machine (JVM). JVM interprets bytecodes. * JVM was first implemented on Sparc/Solaris and PC/Win32. Now ported to many other platforms. * Java applets are Java programs that are retrieved and executed by web browsers through the JVM under tight secure environment. * Web browsers retrieve Java applets according to following tags in the web pages:

<applet code=ResPlotApplet.class width=600 height=500> deprecated or the new more general,

<object codetype="application/java" classid="java:ResPlotApplet.class" width=600 * height=500> <param> are used to specify parameters for the applet. For example,

<APPLET CODE="Animator.class" WIDTH="aNumber" pixels) of the widest frame HEIGHT="aNumber"> pixels) of the tallest frame -- the width (in -- the height (in

<PARAM NAME="IMAGESOURCE" * VALUE="aDirectory"> -- the directory that has the animation frames (gif, jpg) All other types of java programs are called Java applications. * Examples: * Network Restoration Applet: User specifies two end node of a failed link. The applet retrieves the simulation results of two network restoration algorithms (twoprong and rreact) in two

corresponding files at original web server site, and plot the results. * SUN Java demos: o MoleculeViewer o SimpleGraph o SortDemo o BarChart o Animator o JumpingBox

Java is safe

* When a Java applet is downloaded, the bytecode verifier of the JVM verifies to see if it contains bytecodes that open, read, write to local disk. * Java applet can open new window but they have Java log to prevent them from being disguised as system window (for stealing password).

* Java applet is not allowed to connect back to other servers except that hosts itself. * This secure execution environment is called sand box model. * JDK 1.1 extends this tight security with digitally signed applet using jar file. * More detailed fine grained security levels are planned for future release.

Java Development Kit

* The current release is JDK 1.1.7A. It is free for download, containing documents, demos, library, bin/utilities, and Java API packages. * Java Application Programming Interface (API) consists of classes for programming: o java.applet.*: for applet context and interface to browsers

o java.lang.*: variable, string manipulation, exception handing, thread. o java.io.*: File I/O through [buffered] input/outputStream, o java.awt.*: Abstract Window Toolkit (AWT) for window/GUI design, image creation and manipulation o java.util.*: hashtable, stringTokenizer (simple split), date, random, bitset, vector. o java.net.*: url, urlconnection for connecting to original web servers, socket o java.math.*: math functions. o java.sql: for Java-Database interface * Extended APIs: o Media API for sound, video, 3D, VRML o Commerce API o Servlet API * JDK 1.2 will soon be released.

Java Applet Development Environment

* Make sure the CLASSPATH in your autoexec.bat does not contain local directory, or just comment it out. They triggers the security alarm saying that the applet trying access to local drive. * Use Jbuilder2 (in our PC lab). It contains o java source code editor o class browser o debugger o visual GUI design tool similar to VBasics. o wizard for guiding the java application, java applet, java class development. o extensive java beans and libraries for Database access and enhanced GUI design. * Create new Java Applet by o first create a project folder by

+ select the File/New Project, the project wizard window appears + replace the untitle string in the file textfield with your project name, say cs301hw6. + replace the title of the project, click finish, a project template will appear. o then create the Java applet template by + select File/New + click on the Applet icon + fill in the information in the applet creation dialog box (choose the core Java and Swing only option) + write java code in the created template. + control-s to save file the <jbuilder2 home>myprojects\cs301hw6 directory, where <jbuilder2home> is the directory setup for jbuilder2 in your system. + select build/make "CompareCookieSales.java", it will compile the

code, show the error if any, and save the class byte code in <jbuilder2home>myclasses\CompareCookieSales.cl ass + ftp the .java code and .class code (note there may be more than one .class generated) back to the web server directory. + Make sure the case of the class file name is correct after the file transfer. * Download JDK1.1.7A (you can also try JDK1.2RC2 a beta release) to your own PC. * Use text editor to create .java source code. * Reference document web page, http://java.sun.com/products/jdk/1.1/docs/api/packag es.html * Use " javac ResPlot.java" to compile the java code. * Create a web page with the object or applet tag to reference the Java Applet.

Basics of Applet Programming Operators and Their Precedence The following table shows the precedence assigned to Java's operators. The operators in this table are listed in precedence order: the higher in the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with a relatively lower precedence. Operators on the same line have equal precedence. postfix operators [] . (params) expr++ expr--

unary operators ++expr --expr +expr -expr ~ ! creation or cast new (type)expr multiplicative additive shift +<< >> >>> < > <= >= instanceof == != */%

relational equality

bitwise AND

& ^ |

bitwise exclusive OR bitwise inclusive OR logical AND logical OR || conditional ? : &&

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

When operators of equal precendence appear in the same expression, some rule must govern which is evaluated first. In Java, all binary operators except for the assignment operators are evaluated in left to right order. Assignment operators are evaluated right to left. Control Flow Statements A statement such as the while statement is a control flow statement, that is, it determines the order in

which other statements are executed. Besides while, similar to C, the Java language supports several other control flow statements (except the exception handling), including:

Statement Keyword decision making loop if-else, switch-case

for, while, do-while try-catch-finally, throw

exception

miscellaneous break, continue, label: , return

Note: Although goto is a reserved word, currently the Java language does not support the goto statement. Handling errors with Expression using Try, Catch, and Throw Basic Steps:

* All Applet source code starts with

import java.applet.*; and other import statements for packages used in the applet such as * import java.awt.*; import java.io.*; import java.lang.*; import java.net.*; import java.util.*; It then starts with a class definition like:

public class Chart extends java.applet.Applet { // followed by a list of variables or objects declaration // Button b1 = new Button("play"); Button b2 = new Button("stop"); Button b3 = new Button("resume"); TextField tf = new TextField("Message here", 50);

TextArea ta = new TextArea("please wait...", 10, 40); * } The main class contains four basic Applet methods:

public void init() { // for any initialization code performed during loading time of the applet // such as loading graphics, initialize variables, creating objects // add() is used to insert the objects into the area allocated for the applet add(b1); add(b2); add(b3); add(tf); add(ta); } public void start() { // implement the main action of the applet behavior

// it is also called by browser to restart after it was stopped. } public void stop() { // stop an applet's execution but leaves resources intact so it can restart. } public void destroy() { // release all its resources // typically happens when the user leaves the page containing the applet. * } Many Applet only needs to implement init() * For control and user input, Button, TextField, TextArea, Canvas objects are created in init()

and special method action() is called when event happens public boolean action(Event e, Object o) {

if (e.target instanceof Button) { String s = (String) o; if (s.equals("play") { tf.setText("play button is pushed"); } else if (s.equal("stop") { ta.setText("stop button is pushed"); } else { ta.appendText("resume button is pushed"); } return true; } return false; * } Try this basic example.

Abstract Window Toolkit (AWT) Tutorial from Netscape

Using AWT Components: http://owl.uccs.edu/~cs301/java/awt/oldui/componen ts/using.html

Layout the Components in a container: http://owl.uccs.edu/~cs301/java/awt/oldui/layout/ind ex.html

Note that there are new GUI packages such swing and Java 2D graphics recommended by Netscape. They are great for making Java applications with GUI, but there are still a lot of browsers do not support that. They require JDK1.2 compatible viewer or Java plug in.

"Java Plug-in software enables enterprise customers to direct Java applets or JavaBeansTM components on their intranet web pages to run using Sun's Java

Runtime Environment (JRE), instead of the browser's default Java runtime. This enables an enterprise to deploy Java applets that take full advantage of the latest capabilities and features of the Java platform and be assured that they will run reliably and consistently. " -http://java.sun.com/applets/index.html.

Using JFC/SWING to create GUI The swing components in Java Foundation Classes (JFC) is the new package in JDK1.1 and JDK1.2 for supporting GUI design in Java applications and applets. It provides much more features to those of AWT. For examples,

* allow images on buttons/labels, * dynamically change of borders, * component can be round,

* specify look and feels (Java, Windows, CDE/Motif). * wider selection of components * not using native code (more portable)

Unfortunately, Sun recommends that SWING and AWT components not mix. Their drawing sequence are basically different. "Heavyweight" AWT components such as menu, scrollpane, canvas, and panel always draw on top of "lightweight" SWING components.

Tutorial on using GridBagLayout.

Note that the current tutorial on java.sun.com is going through major revision. Some web pages, such as the layout manager tutorial, event hung the whole browser. Use them with caution. 12/3/98.

Example for using GridBagLayout and submit data to a CGI script http://owl.uccs.edu/~cs301/java/Register.html and Register.java Goal:

* Illustrate the use of the GridBagLayout manager and AWT components. * Learn how to exchange data between Applet and CGI script using URL.

How we arrange the GridBagLayout using GridBagConstraints:

* Here we create a title as a Label and set gbc.anchor = GridBagConstraints.NORTH.

* We have login and address Labels and set their gbc.anchor = GridBagConstraints.WEST and gbc.gridwidth = 1. * The login TextField and address TextArea are set with gbc.grdiwidth = GridBagConstraints.REMAINDER. * The submit Button is set with gbc.anchor = GridBagConstraints.CENTER and padded with 10 pixels on each side using gbc.insets = new Insets(10,10,10,10); * Finally the return result TextArea is set with gbc.anchor = GridBagConstraints.SOUTH and gbc.grdiwidth = GridBagConstraints.REMAINDER.

Basic steps for using the applet:

* When the submit button is hit, the action method first performs www-url-encode on the content of address TextArea, then puts the fields of

the login and address in the name-value pair format attached at the end of the url. * Create a URL with it, which in effect submit the data the corresponding CGI script on the server side. * The registerData.pl saves the data in a file and return a web page that is then displayed in the result TextArea.

Example for plotting the cookie sale of a particular year. http://owl.uccs.edu/~cs301/java/plotdemo/CookieSal es.html and CookieSales.java. Goal:

* Learn how to use the graphic drawing capability of the AWT. * Learn how to retrieve data files from the web server.

Here are the basic steps for using the Applet:

* After the user selects the year in the choice menu and hits the plot button, the action method creates the url string by concatenating http://owl.uccs.edu/~cs301/java/plotdemo/data/ with CookieSale<year>. * It then creates an URL object with the string and open a DataInputStream for reading the 12 month sale data from the web server into an array. * Each line of the data file contains the month and box numbers of the cookie sale. * The data file is displayed in the contents TextArea. * It then sets the array in the CookieSalesCanvas class and asks it to plot the bar chart based on the data.

* drawRect() and fillRect() are used to draw the bar of each month.

Reasons for Extending Canvas Class

* For AWT components, we do not have extend classes unless there is a special need. * For plots using Canvas class, we have a special requirement for handling the redrawing when the part or whole of the canvas area is destroyed due to the resizing of the applet or window hierarchy changes (other window pops up). * Those destroyed areas need to be redrawn. * The paint(Graphics g) method is designated for handling the redrawing and the first drawing of the area. * It will be given the area that needs to be redrawn.

* It needs to know how to redraw the area --> needs to have access to the original source data. * Therefore, we extend the canvas class with additional variables, such as Year and Sv[][] for holding a copy of the original source data. * Here we use a setValue() to copy the source data from the applet to CookieSalesCanvas. * In the paint(), we use the basic drawing functions create the content.

Important Site

* http://java.sun.com * Applet collections: http://java.sun.com/applets/index.html * Java Tutorial * http://java.sun.com/products/jdk/1.1/docs.html: main document web page for JDK

* http://www.gamelan.com: depository for java applets and links to related web sites. * http://www.javaworld.com: magazine, article, source code, news. * http://www.yahoo.com/Computers_and_Internet/Pro gramming_Languages/Java *

Good References

* The Java Tutorial by Mary Campione and Kathy Walrath, Addison Wesley, 1996 Note that there is a new book "The Java Tutorial Continue" will appear Dec 98. * Java How to Program, by Deitel & Deitel, Prentice Hall, 1997. * Java 1.1 Unleashed 3rd ed., Sam.net,

* Graphic Java, Mastering the AWT, 2nd ed., by David M, Geary, Prentice Hall, 1997. *

Debug Java Applet

* Use showStatus() which shows string on browser's status window. * Create a TextArea or TextField for displaying intermediate results. * Use JDB that comes with JDK. * Use tools such as Jbuilder, Visual cafe, MS J++.

You might also like