(syllabus and calendar)

Extra topics, not in the first 10 chapters

Extra

threads - zip11 of examples


applets


javadoc overview

Thread examples

See thread-examples.htm


Swing GUI

swing-examples.zip

Simple Swing application the displays the title of a JFrame:

public class HelloJava
{
    public static void main(String[] args)
    {
    javax.swing.JFrame frame = new javax.swing.JFrame( "Hello, Java!" );
    frame.setSize( 300, 300 );
    frame.setVisible( true );
    }
}

Next, we add text to the JFrame:

import javax.swing.*;
public class HelloJava
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame( "HelloJava" );
        JLabel label = new JLabel("Hello, Java!", JLabel.CENTER );
        frame.getContentPane().add( label );
        frame.setSize( 300, 300 );
        frame.setVisible( true );
    }
}

This example of a Swing GUI using the moving coordinates of the end-user dragging a mouse.


Applets

The JDK (or SDK) contains a directory with sample applets.

Let's open the HTML file in for the fractal applet.

Applet Viewer

You can run an applet by using the lightweight applet viewer the comes with the JDK.
The applet viewer can help you debug and test your applet.
Later, you can write an HTML page that references the applet.

The applet viewer resides in the bin directory of your JDK.
On a Windows system, it might be:
D:\java\j2sdk1.4.2_03\bin\appletviewer.exe

You can launch an applet by giving the relative path to the HTML page for the applet. For example:

D:\java\j2sdk1.4.2_03\bin>appletviewer ..\demo\applets\Fractal\example1.html
which lauches the AppletViewer and runs a dynamic example:

Note: TextPad runs an applet with the appletviewer when you press Ctrl-3.

Here is another example:

D:\java\j2sdk1.4.1_01\bin>
appletviewer ..\..\teachjava\spring2003\session8\SimpleApplet.java

Example: animated blobs at http://www.mandrixx.net/javasimple.html

Sun's web site for applets: http://java.sun.com/applets/

Sun's tutorial on writing applets: http://java.sun.com/docs/books/tutorial/applet/overview/index.html
and includes a dog barking! http://java.sun.com/docs/books/tutorial/applet/appletsonly/sound.html

What is an applet?

A Java application, when the Java interpreter in the Java Virtual Machine executes the bytecode, is a normal program in native machine code that can make calls directly into the operating system and can access the file system.

An applet is more limited than an application.

http://java.sun.com/j2se/1.4.2/docs/api/java/applet/Applet.html
An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application.
The
Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer.
The
Applet class in part of a package called java.applet.
Just as most Exceptions are a subclass of java.lang.Exception, so all Applets are a subclass of java.applet.Applet.

A Java applet is a .class file you can download and run from an HTML page as you surf the internet (or an intranet). An applet is limited to a "sandbox" for security: it runs inside of an HTML browser, such as Mozilla Firefox or Microsoft Internet Explorer. The "security sandbox" means the applet cannot navigate your file system to change or copy your files. An applet is a virtual application that is locked inside another application, the browser.

An HTML browser is a special application that interprets HTML, renders text and images, and can contain a version of the JVM. The applet runs inside the JVM of the browser.

The "sandbox" is a security layer around the applet that prevents the applet from harming you or your computer:
       http://java.sun.com/docs/books/tutorial/applet/overview/security.html

Each browser has a SecurityManager object that implements its security policies. When a SecurityManager detects a violation, it throws a SecurityException. Your applet can catch this SecurityException and react appropriately.

Java applets are slower than Java applications but faster than the unrelated JavaScript - http://en.wikipedia.org/wiki/Java_applet

----------------------------------------------

(These restrictions can be customized by the client through the browser or by modifying the security properties file.)

Signed Applets

Signed applets are applets that are certified to come from a registered (and therefore hopefully trustworthy) source.

The provider of a signed applet can ask the end-user for permission to allow the applet freedom from the sandbox restrictions.

If the user's browser detects a signed applet, it displays the certificate and prompts the user to respond by trusting this applet, all applets from this applet provider, or declining to trust this applet.

To sign your applet, you work with a third party Certificate Provider (http://en.wikipedia.org/wiki/Certificate_Authority), such as VeriSign, http://www.verisign.com/products/signing/index.html or GoDaddy. The Certificate Provider provides a digital signature, or key, that authenticates you as the provider of the applet and guarantees that the applet code has not been alerted. 
VeriSign does not verify that the code in the applet is safe. VeriSign takes some business measures to attempt to verify that you are who you say you are. One such measure is accepting payment from you.

The client communicates both with the applet provider and the third party.

A signed applet has none of the applet restrictions, and has the privileges of an application even though it runs in the browser.

Despite big hopes in the early days of Java, neither applets nor signed applets became the killer app of the internet. In general, applets are quite slow, and other technologies, such as Adobe Flash, Microsoft Silverlight, and HTML5, have become popular.

A signed applet is an applet to which the end-user grants the same powers as an application. For example, the applet that installs the browser plug-in to update the browser JVM is a signed applet. VeriSign checks to make sure that it is Sun that offers the applet.

Your SDK provides a directory with demonstration applets. The path might be something similar to the following.
D:\java\j2sdk1.4.2_03\demo\applets


Suppose that I want to see one string inside a browser.
I need skeleton HTML that references the bytecode.

Here is the skeleton applet code.


This version has a Graphics object, which provides a sort of canvas against which text (and images) can be rendered by calling the paint method.

HelloWorld Applet in an HTML Page

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {
    public void paint(Graphics g) {
        g.drawString("Hello world!", 50, 25);
    }
}

 

I can run this applet by opening the following HTML file in a browser:

<html>
   <head>
      <title>HelloWorld</title>
   </head>
   <body>
      <applet code="HelloWorld.class" width=200 height=100>
      </applet>
   </body>
</html>

I can name this HTML file HelloWorld.htm or any name I want.

This applet calls the drawString method of the Graphics class in the java.awt package, Java's earliest package for creating graphical user interfaces.

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics.html
public abstract void drawString(String str,
                                int x,
                                int y)

Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the leftmost character is at position (xy) in this graphics context's coordinate system.

The Swing package is more recent than the awt package, but awt package has the advantage of being built-in to most browsers.

About Swing

The package is javax.swing and javax means java extended.  http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html

Swing provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.

Swing's UIManager.setLookAndFeel method can be set for the native OS of the system, or for the look typical of Macintosh, UNIX, Windows, or Swing's own cross-platform look, which is called metal.

HelloWorld in the JDK's AppletViewer

 


How does an applet run?

The differences between an applet and an application are that an applet:

D:\java\j2sdk1.4.1_01\bin>
appletviewer ..\..\teachjava\spring2003\session8\AppletSkel.java


This example has motion because it starts a thread to display a moving banner of text. A thread is similar to a process but a thread shares memory with the application that spawned it. A process runs in its own memory space. How does the object-oriented language, Java, create a thread object?

Here is the code:

D:\java\j2sdk1.4.1_01\bin>
appletviewer ..\..\teachjava\spring2003\session8\AppletSkel.java


Debugging an Applet

http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/appletviewer.html

-debug
Starts the applet viewer in the Java debugger, jdb, thus allowing you to debug the applets in the document.

You can debug applets using the -debug option of appletviewer. When debugging applets, it's best to invoke appletviewer from the directory that contains the applet's HTML file. For example, on the PC:
cd demo\applet\TicTacToe
..\..\bin\appletviewer -debug example1.html


More examples of the HTML necessary to run an applet.

Or:

Basic HTML to embed an applet in a web page

To embed an applet in a web page, you must write HTML code to reference the the applet's class file and the size of the applet.

Sun describes this at http://java.sun.com/products/jdk/1.1/docs/guide/misc/applet.html

<applet code="MyApplet.class" width=100 height=140></applet>

Minimal HTML to display an applet

The glossary applet at http://www.wordesign.com/java/glossary/ uses very little HTML to display a glossary of Java terms:

<html>
<head>
<title>For the title bar of the browser's window--can be blank</title>
</head>
<body>
 some introductory text, if you want<br>
<APPLET CODE="com.yourCompany.yourProductPackage.YourApplet.class" height="80%" width="80%"></APPLET>
</body>
</html>

Note: The applet tag requires the fully qualified name of the class, which is the name of the class package followed by the class name.

HTML that references an applet in a package

If you declare in your java source code that your extension of the Applet class belongs to a package, your HTML page must reference the package as well as the class file.

(This also matches the file system because InPackage.class resides in a subdirectory called myappletpackage.)

And here's the HTML:


Creating an applet

To create an applet, you extend the Applet class and override methods of the java.applet package.

extending the applet class

Java defines the applet object in the java.applet package.

Key method definitions are:

Basic methods: init(), paint()

The init() method is called when the browser is done loading the applet. Using this method, you will typically any initializations that the applet needs.

An applet inherits the paint() method from the Component class. The paint() method takes as argument an instance of the Graphics class. The graphics object provides methods to draw geometric shapes and text.

For your first applet, you will typically override the paint() method to do your custom drawing.

Demonstration of an Applet

**********************************

Java Applet Example

import java.awt.Graphics;
import java.awt.Color;
public class HelloApplet extends java.applet.Applet {
	public void paint(Graphics g) {
		g.setColor(Color.red);
		g.drawString("Hello World!", 5, 50);
	}
}

Your HTML page references the applet's compile bytecode class name and defines the space for the browser display the running applet:

<HTML>
   <BODY>
      <applet code="HelloApplet.class" width=350 height=130>
      </applet>
   </BODY>
</HTML>

Parameters in the HTML page for an applet

passing parameters

You can pass parameters to an applet from the HTML code. 
For example, your HTML page might have a parameter, language, with a value, French, that tells the applet to display the French version of the applet.

The syntax to add parameters to your HTML page is:

http://java.sun.com/products/jdk/1.1/docs/guide/misc/applet.html

<applet code="appletname.class" width=400 height=75>
 <param name="language" value="French"> 
 </applet>

How the applet gets parameter values from your HTML page

The applet class provides a method called getParameter() that takes as input a String that represents the name of the parameter. In our example, the parameter would be language. The return value of the getParameter() method is the value of the parameter. In our example, the parameter value is French.

size

The client can resize your applet if you specify the applet size as a percentage of the browser window. Alternatively, you can specify the applet size as a specific number of pixels.


Event Handling in an Applet

Graphical user interface's (GUI) are event-driven. They respond to the end-user's actions, such as clicking on buttons.
Java provides interfaces and classes to support event-driven programming.

http://java.sun.com/j2se/1.4.2/docs/api/java/util/EventListener.html

Two interfaces that support event-drive programming are MouseListener and MouseMotionListener.

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseListener.html

The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a component. (To track mouse moves and mouse drags, use the MouseMotionListener.)

The class that is interested in processing a mouse event either implements this interface (and all the methods it contains) or extends the abstract MouseAdapter class (overriding only the methods of interest).

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseMotionListener.html

The MouseEvents applet handles mouse events as they occur.
This applet shows on the status bar the current position of the mouse, and also displays whether the mouse has entered or exited the applet area..

AppletViewer view (no HTML file specified):

Browser View (an HTML page opened):

Here's the code that monitors the actions of the mouse.

Sun provides this demonstration of event handling:

http://java.sun.com/docs/books/tutorial/applet/overview/componentMethods.html

   EVENTS AND APPLETS

  1. Does a signed applet have the same capabilities as an application?
  2. Every applet is a subclass of the _____________ class of the __________________ package.
  3. How come applets do not have a main() method?
  4. What is an event?
  5. What reacts when an event occurs?


Javadoc overview

Javadoc is how Sun documents in the core application programming interface (API) of Java (see http://java.sun.com/javase/6/docs/api/), and how you can document the APIs you provide to other software developers. Javadoc output is HTML, with a navigation frame and a content frame. The javadoc utility extracts documentation from source code file javadoc comments placed immediately above the following:

Note: It would not make sense to publish private members. The default (undeclared) visibility, which is neither public nor protected, is also NOT used for javadoc.

Example of javadoc

  1. Download the zip that has an example of javadoc for two packages:
  2. Read the ReadMe in the zip.

Steps to run this javadoc
1. cd to the directory when you unzipped the archive, for example,
    D:\_08summer\javadoc-stuff
2. compile from above the packages
    javac demojavadoc\*.java
    javac mypack\*.java
3. Run the app
    java demojavadoc.JavadocDemo
4. Run javadoc for BOTH packages, using -d before the directory name to hold the HTML output
    javadoc -version -author -d output2 demojavadoc\*.java mypack\*.java
5. View the output in an HTML browser:
    file:///D:/_08summer/javadoc-stuff/index.html


Adding javadoc to Your Source Code

Javadoc comments begin with /** and end with */

There are special tags, starting with @, for documenting a parameter, return value, and other items.

This class description includes HTML tags, which are optional.


 

This method description documents the parameters and return value.

 

This method description indicates that this method (or method signature) is obsolete in the current version.



javadoc - Generating the HTML Output

 

  1. Create a directory for your Java source code (.java files). In this example, the source code files are inside a directory called groovy, and the source code says that each class belongs to the groovy  package.
  2. Create a separate directory for your javadoc output (.html files), such as output-groovy.

  1. Create a package summary file.
    javadoc requires that it be named package-info.java and that it be in the same directory as your source code files.
  2. Put a summary comment about the package in the package summary file.

/**
* The groovy package is a set of examples that
* illustrate the use of javadoc tags.
* Note: This package summary, like ALL package
* summaries, must be in a file named
* <code>package-info.java</code>
* @version 1.1
* @author Your Name
*/
package groovy
;

  1. Navigate one directory above the source code directory (from the groovy directory, cd .. at the command prompt).

    D:\__07Fall\9\javadoc>
     
  2. Compile all the classes in the directory,

    javac groovy/*.java
     
  3. Navigate to the directory that contains the source code files.

    cd groovy

     
  4. Run javadoc.

    javadoc -version -author -d D:\__07Fall\9\javadoc\output-groovy *.java

    Note: -version and -author tells javadoc to include the version number and author name(s), and -d specifies the directory for the HTML output.
    So the syntax is:
        javadoc   option(s)   directory_for_output    location_of_files_with_javadoc_comments
     
  5. Open the index.html file:

10. Verify that the package summary and author names appear.

I will run an example where I first cd to

D:\_08summer\javadoc-stuff\zip_of_examples\javadoc

and then give this command

javadoc -version -author -d myOutput groovy\*.java

For More Information