+ All Categories
Home > Documents > swet_Java Applet Tutorial

swet_Java Applet Tutorial

Date post: 30-May-2018
Category:
Upload: swet-bhushan
View: 221 times
Download: 0 times
Share this document with a friend

of 30

Transcript
  • 8/14/2019 swet_Java Applet Tutorial

    1/30

    Java Applet Tutorial

    This site is meant to be a quick-and-dirty introduction to writing Java applets. A set of

    example applets are given to be used as exercises. Feel free to download the source

    code herein, try it out on your own machine, and modify it.

    Designers and artists: this tutorial emphasizes visual and interactive aspects of

    applets. It was made especially for people wishing to create small, graphical,

    expressive forms with Java. However, if you have no programming experience at all,

    you'll probably need additional learning resources. Please see the note below for

    first-time programmers.

    Before getting started, you'll need a compiler for Java, so that you can translate source

    code into something executable. You could, for example, download Sun's Java

    Software Development Kit (abbreviated as JDK or SDK), which includes a compiler,

    utilities, example applets, and a boat-load of documentation. (Mac users can try here,here and here.) Be sure to get the Java SDK and not the JRE (Java Runtime

    Environment) -- the former allows you to compile java programs, the latter only

    allows you to run them.

    After getting a compiler, you can try out the examples. The first one, "Drawing

    Lines", walks you through the process of creating an applet. Please note that lessons

    9-12 are unfinished, as I have yet to get around to completing them.

    1 Drawing Lines

    2 Drawing Other Stuff

    3 Color- introduces arrays4 Mouse Input - introduces showStatus( ) and Vector

    5 Keyboard Input

    6 Threads and Animation - introduces System.out.println( )

    7Backbuffers - introduces Math.random( ) and Graphics.drawImage( )

    8 Painting

    9 Clocks

    10Playing with Text - introduces 2D arrays and hyperlinks

    113D Graphics - introduces classes

    12Odds and Ends

    http://java.sun.com/j2se/1.3/http://java.sun.com/docs/books/tutorial/getStarted/cupojava/mac.htmlhttp://java.sun.com/cgi-bin/java-ports.cgihttp://www.apple.com/java/http://www.dgp.toronto.edu/~mjmcguff/learn/java/01-drawingLines/http://www.dgp.toronto.edu/~mjmcguff/learn/java/02-drawingOtherStuff/http://www.dgp.toronto.edu/~mjmcguff/learn/java/03-color/http://www.dgp.toronto.edu/~mjmcguff/learn/java/04-mouseInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/05-keyboardInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/06-threads/http://www.dgp.toronto.edu/~mjmcguff/learn/java/07-backbuffer/http://www.dgp.toronto.edu/~mjmcguff/learn/java/08-painting/http://www.dgp.toronto.edu/~mjmcguff/learn/java/09-clocks/http://www.dgp.toronto.edu/~mjmcguff/learn/java/10-text/http://www.dgp.toronto.edu/~mjmcguff/learn/java/11-3d/http://www.dgp.toronto.edu/~mjmcguff/learn/java/12-miscellaneous/http://www.dgp.toronto.edu/~mjmcguff/learn/java/12-miscellaneous/http://www.dgp.toronto.edu/~mjmcguff/learn/java/11-3d/http://www.dgp.toronto.edu/~mjmcguff/learn/java/10-text/http://www.dgp.toronto.edu/~mjmcguff/learn/java/09-clocks/http://www.dgp.toronto.edu/~mjmcguff/learn/java/08-painting/http://www.dgp.toronto.edu/~mjmcguff/learn/java/07-backbuffer/http://www.dgp.toronto.edu/~mjmcguff/learn/java/06-threads/http://www.dgp.toronto.edu/~mjmcguff/learn/java/05-keyboardInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/04-mouseInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/03-color/http://www.dgp.toronto.edu/~mjmcguff/learn/java/02-drawingOtherStuff/http://www.dgp.toronto.edu/~mjmcguff/learn/java/01-drawingLines/http://www.apple.com/java/http://java.sun.com/cgi-bin/java-ports.cgihttp://java.sun.com/docs/books/tutorial/getStarted/cupojava/mac.htmlhttp://java.sun.com/j2se/1.3/
  • 8/14/2019 swet_Java Applet Tutorial

    2/30

    All of these examples were designed to be small and, hopefully, easy to absorb. If you

    couldn't find information here that you need, you might try Sun's website, which has

    copious documentation on Java, along with online tutorials and examples. You might

    also try the Java FAQ, a copy of which can be found by searching for "java faq" in any

    good search engine (or just try here -- the same site also hosts a tutorial).

    If you're looking for books on Java, O'Reilly publishes some good ones, although they

    are most useful to people with at least a bit of prior programming experience.Java in

    a Nutshellby David Flanagan (in its 3rd edition, at the time of writing) covers thebasic features of Java, including the syntax of the language, data structures,

    object-oriented features, and threads. Determined novices with no programming

    experience may find it useful.Java Foundation Classes in a Nutshellby David

    Flanagan describes how to create GUIs with widgets and how to draw basic graphics,

    among other things.Java 2D Graphics by Jonathan Knudsen, also published by

    O'Reilly, discusses in detail the graphics features of the Java 2 platform.

    First-time programmers will probably find that the explanations given in this

    tutorial are too brief and leave out too many details. Basic information on the Java

    language can be found here (try to focus on understanding the syntax of variables,

    expressions, loops, and flow control structures at first -- we hardly make use of anyobject-oriented concepts in this tutorial). There are some books on Java for first-time

    programmers: this site recommendsJava: An Introduction to Computer Science and

    Programmingby Walter Savitch et al.,Problem Solving With Java by Elliot B.

    Koffman and Ursula Wolz, andIntroduction to Programming Using Java: An

    Object-Oriented Approach by David M. Arnow and Gerald Weiss. You might also try

    getting a feel for some basic programming concepts by learning a simpler language

    first, such as DBN.

    Terminology : Note that the termfunction is used in this tutorial in place of the more

    modern (and object-oriented) term method.

    http://www.dgp.toronto.edu/~mjmcguff/learn/java/01-drawingLines/http://java.sun.com/http://sunsite.kth.se/javafaq/javafaq.htmlhttp://sunsite.kth.se/javafaq/javatutorial.htmlhttp://www.oreilly.com/http://java.sun.com/docs/books/tutorial/java/index.htmlhttp://www.apl.jhu.edu/~hall/java/Java-Books.html#Java-Books-Tutorials1http://dbn.media.mit.edu/http://dbn.media.mit.edu/http://www.apl.jhu.edu/~hall/java/Java-Books.html#Java-Books-Tutorials1http://java.sun.com/docs/books/tutorial/java/index.htmlhttp://www.oreilly.com/http://sunsite.kth.se/javafaq/javatutorial.htmlhttp://sunsite.kth.se/javafaq/javafaq.htmlhttp://java.sun.com/http://www.dgp.toronto.edu/~mjmcguff/learn/java/12-miscellaneous/http://www.dgp.toronto.edu/~mjmcguff/learn/java/11-3d/http://www.dgp.toronto.edu/~mjmcguff/learn/java/09-clocks/http://www.dgp.toronto.edu/~mjmcguff/learn/java/08-painting/http://www.dgp.toronto.edu/~mjmcguff/learn/java/08-painting/http://www.dgp.toronto.edu/~mjmcguff/learn/java/07-backbuffer/http://www.dgp.toronto.edu/~mjmcguff/learn/java/06-threads/http://www.dgp.toronto.edu/~mjmcguff/learn/java/05-keyboardInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/05-keyboardInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/04-mouseInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/04-mouseInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/03-color/http://www.dgp.toronto.edu/~mjmcguff/learn/java/03-color/http://www.dgp.toronto.edu/~mjmcguff/learn/java/02-drawingOtherStuff/http://www.dgp.toronto.edu/~mjmcguff/learn/java/01-drawingLines/
  • 8/14/2019 swet_Java Applet Tutorial

    3/30

    About these web pages :These exercises were a joy to prepare once I figured out how to write a Perl script that could take the

    documentation and .java source files I wrote and generate .html files with them. The script also

    generated the little navigation bars at the top of each exercise page, and made it easy for me to play

    with different color schemes.Thanks to Richard Streitmatter-Tran for encouraging me to create these lessons !

    This tutorial is ( C ) 2000 Michael McGuffin, all rights reserved.

    Exercise 1: Drawing Lines

    Here's the source code for a first applet:

    import java.applet.*;import java.awt.*;

    public class DrawingLines extends Applet {

    int width, height;

    public void init() {width = getSize().width;height = getSize().height;setBackground( Color.black );

    }

    public void paint( Graphics g ) {g.setColor( Color.green );for ( int i = 0; i < 10; ++i ) {

    g.drawLine( width, height, i * width / 10, 0 );}

    }}

    Start up a plain text editor and type in the source code. It's important that you use a

    plain ASCII text editor (such as "Notepad" on Windows, "SimpleText" on Mac, or

    "vi" or "emacs" on UNIX) to enter the source code; don't use a word processing

    application (such as "WordPerfect" or "Word") since they use a proprietary format forfiles. If you don't want to do any typing, you can download the source file. Save the

    file as DrawingLines.java . It's important that the filename match the class name in

    the source code.

    Now, you have to compile the source code to generate a bytecode file called

    DrawingLines.class . If you're using Sun's Java Software Development Kit, you can

    compile by typing javac DrawingLines.java at a command prompt (on Windows,

    this is done within an MS-DOS shell). Check that the .class file was indeed

    generated.

    Then, create a .html file containing the following line:

    http://www.dgp.toronto.edu/~mjmcguff/learn/java/genHtml.perlhttp://www.dgp.toronto.edu/~mjmcguff/learn/java/01-drawingLines/DrawingLines.javahttp://www.dgp.toronto.edu/~mjmcguff/learn/java/01-drawingLines/DrawingLines.javahttp://www.dgp.toronto.edu/~mjmcguff/learn/java/genHtml.perl
  • 8/14/2019 swet_Java Applet Tutorial

    4/30

    (If the .html file is not in the same directory as the .class file, you'll have to add a

    codebase="..." attribute specifying the path to the class file. More information on

    the tag can be found here.) When you view the .html file in a web browser,

    you should see something like this:

    Here's a second version of the same source code, this time with comments:

    import java.applet.*;import java.awt.*;

    // The applet's class name must be identical to the filename.public class DrawingLines extends Applet {

    // Declare two variables of type "int" (integer).int width, height;

    // This gets executed when the applet starts.public void init() {

    // Store the height and width of the applet for futurereference.

    width = getSize().width;height = getSize().height;

    // Make the default background color black.setBackground( Color.black );

    }

    // This gets executed whenever the applet is asked to redrawitself.

    public void paint( Graphics g ) {

    // Set the current drawing color to green.g.setColor( Color.green );

    // Draw ten lines using a loop.// We declare a temporary variable, i, of type "int".// Note that "++i" is simply shorthand for "i=i+1"for ( int i = 0; i < 10; ++i ) {

    // The "drawLine" routine requires 4 numbers:// the x and y coordinates of the starting point,// and the x and y coordinates of the ending point,// in that order. Note that the cartesian plane,// in this case, is upside down (as it often is// in 2D graphics programming): the origin is at the

    // upper left corner, the x-axis increases to the right,// and the y-axis increases downward.g.drawLine( width, height, i * width / 10, 0 );

    }}

    }

    [ Home | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 ]

    http://java.sun.com/products/jdk/1.1/docs/guide/misc/applet.htmlhttp://www.dgp.toronto.edu/~mjmcguff/learn/java/http://www.dgp.toronto.edu/~mjmcguff/learn/java/01-drawingLines/http://www.dgp.toronto.edu/~mjmcguff/learn/java/03-color/http://www.dgp.toronto.edu/~mjmcguff/learn/java/04-mouseInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/05-keyboardInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/06-threads/http://www.dgp.toronto.edu/~mjmcguff/learn/java/07-backbuffer/http://www.dgp.toronto.edu/~mjmcguff/learn/java/08-painting/http://www.dgp.toronto.edu/~mjmcguff/learn/java/09-clocks/http://www.dgp.toronto.edu/~mjmcguff/learn/java/10-text/http://www.dgp.toronto.edu/~mjmcguff/learn/java/11-3d/http://www.dgp.toronto.edu/~mjmcguff/learn/java/12-miscellaneous/http://www.dgp.toronto.edu/~mjmcguff/learn/java/12-miscellaneous/http://www.dgp.toronto.edu/~mjmcguff/learn/java/11-3d/http://www.dgp.toronto.edu/~mjmcguff/learn/java/10-text/http://www.dgp.toronto.edu/~mjmcguff/learn/java/09-clocks/http://www.dgp.toronto.edu/~mjmcguff/learn/java/08-painting/http://www.dgp.toronto.edu/~mjmcguff/learn/java/07-backbuffer/http://www.dgp.toronto.edu/~mjmcguff/learn/java/06-threads/http://www.dgp.toronto.edu/~mjmcguff/learn/java/05-keyboardInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/04-mouseInput/http://www.dgp.toronto.edu/~mjmcguff/learn/java/03-color/http://www.dgp.toronto.edu/~mjmcguff/learn/java/01-drawingLines/http://www.dgp.toronto.edu/~mjmcguff/learn/java/http://java.sun.com/products/jdk/1.1/docs/guide/misc/applet.html
  • 8/14/2019 swet_Java Applet Tutorial

    5/30

    Exercise 2: Drawing Other Stuff

    The source code:

    import java.applet.*;import java.awt.*;

    public class DrawingStuff extends Applet {

    int width, height;

    public void init() {width = getSize().width;height = getSize().height;setBackground( Color.black );

    }

    public void paint( Graphics g ) {

    // As we learned in the last lesson,

    // the origin (0,0) is at the upper left corner.// x increases to the right, and y increases downward.

    g.setColor( Color.red );g.drawRect( 10, 20, 100, 15 );g.setColor( Color.pink );g.fillRect( 240, 160, 40, 110 );

    g.setColor( Color.blue );g.drawOval( 50, 225, 100, 50 );g.setColor( Color.orange );g.fillOval( 225, 37, 50, 25 );

    g.setColor( Color.yellow );

    g.drawArc( 10, 110, 80, 80, 90, 180 );g.setColor( Color.cyan );g.fillArc( 140, 40, 120, 120, 90, 45 );

    g.setColor( Color.magenta );g.fillArc( 150, 150, 100, 100, 90, 90 );g.setColor( Color.black );g.fillArc( 160, 160, 80, 80, 90, 90 );

    g.setColor( Color.green );g.drawString( "Groovy!", 50, 150 );

    }}

    The resulting applet looks like this:

    For documentation on the Graphics class and the parameters that are passed to

    functions such as drawRect(), fillOval(), etc., go here.

    Please note that some of the member functions in Graphics, such as fillRect(),

    interpret the width and height parameters as measured between pixel edges; hence

    the resulting figure will truly be width pixels wide and height pixels high. However,

    other functions, such as drawRect(), assume dimensions are measured between pixel

    centres; hence the resulting figure will actually be width+1 by height+1 pixels.

    http://java.sun.com/products/jdk/1.3/docs/api/java/awt/Graphics.htmlhttp://java.sun.com/products/jdk/1.3/docs/api/java/awt/Graphics.html
  • 8/14/2019 swet_Java Applet Tutorial

    6/30

    Exercise 3: Color

    In the last lesson, we used a number of colors predefined by Java: Color.red,

    Color.green, Color.magenta, etc. (for a complete list, go here). In this lesson, we learnhow to create arbitrary colors, by specifying an RGB value. The example applets

    below generate spectrums of color and draw something with them.

    The source code for the first applet:

    import java.applet.*;

    import java.awt.*;

    public class DrawingWithColor1 extends Applet {

    int width, height;

    int N = 25; // the number of colors createdColor[] spectrum; // an array of elements, each of type Color

    Color[] spectrum2; // another array

    public void init() {

    width = getSize().width;

    height = getSize().height;

    setBackground( Color.black );

    // Allocate the arrays; make them "N" elements long

    spectrum = new Color[ N ];

    spectrum2 = new Color[ N ];

    // Generate the colors and store them in the arrays.

    for ( int i = 1; i

  • 8/14/2019 swet_Java Applet Tutorial

    7/30

    // As i goes from 1 to N, this color goes from almost pure green to pure red.

    spectrum2[ i-1 ] = new Color( i/(float)N, (N-i)/(float)N, 0 );

    }

    }

    public void paint( Graphics g ) {

    int step = 90 / N;

    for ( int i = 0; i < N; ++i ) {

    g.setColor( spectrum[ i ] );

    g.fillArc( 0, 0, 2*width, 2*height, 90+i*step, step+1 );

    g.setColor( spectrum2[ i ] );

    g.fillArc( width/3, height/3, 4*width/3, 4*height/3, 90+i*step, step+1 );

    }

    }}

    The resulting applet:

    A second example:

    import java.applet.*;

    import java.awt.*;

    import java.lang.Math;

    public class DrawingWithColor2 extends Applet {

    int width, height;

    int N = 25;

    Color[] spectrum;

    public void init() {

    width = getSize().width;

    height = getSize().height;

    setBackground( Color.black );

    spectrum = new Color[ N ];

    // Generate the colors and store them in the array.

    for ( int i = 0; i < N; ++i ) {

    // Here we specify colors by Hue, Saturation, and Brightness,

    // each of which is a number in the range [0,1], and use

    // a utility routine to convert it to an RGB value before

    // passing it to the Color() constructor.

    spectrum[i] = new Color( Color.HSBtoRGB(i/(float)N,1,1) );

    }

    }

    public void paint( Graphics g ) {

  • 8/14/2019 swet_Java Applet Tutorial

    8/30

    int radius = width / 3;

    for ( int i = 0; i < N; ++i ) {

    // Compute (x,y) positions along a circle,

    // using the sine and cosine of an appropriately computed angle.double angle = 2*Math.PI*i/(double)N;

    int x = (int)( radius*Math.cos(angle) );

    int y = (int)( radius*Math.sin(angle) );

    g.setColor( spectrum[ i ] );

    g.drawString( "Color", width/2+x, height/2+y );

    }

    }

    }

    The output:

    Exercise 4: Mouse Input

    The source code:

    import java.applet.*;import java.awt.*;import java.awt.event.*;

    public class Mouse1 extends Appletimplements MouseListener, MouseMotionListener {

    int width, height;int mx, my; // the mouse coordinatesboolean isButtonPressed = false;

    public void init() {width = getSize().width;height = getSize().height;setBackground( Color.black );

    mx = width/2;my = height/2;

    addMouseListener( this );addMouseMotionListener( this );

    }

    public void mouseEntered( MouseEvent e ) {// called when the pointer enters the applet's rectangular area

    }public void mouseExited( MouseEvent e ) {

    // called when the pointer leaves the applet's rectangular area}public void mouseClicked( MouseEvent e ) {

    // called after a press and release of a mouse button

  • 8/14/2019 swet_Java Applet Tutorial

    9/30

    // with no motion in between// (If the user presses, drags, and then releases, there will

    be// no click event generated.)

    }public void mousePressed( MouseEvent e ) { // called after a

    button is pressed down

    isButtonPressed = true;setBackground( Color.gray );repaint();// "Consume" the event so it won't be processed in the// default manner by the source which generated it.e.consume();

    }public void mouseReleased( MouseEvent e ) { // called after a

    button is releasedisButtonPressed = false;setBackground( Color.black );repaint();e.consume();

    }

    public void mouseMoved( MouseEvent e ) { // called during motionwhen no buttons are down

    mx = e.getX();my = e.getY();showStatus( "Mouse at (" + mx + "," + my + ")" );repaint();e.consume();

    }public void mouseDragged( MouseEvent e ) { // called during

    motion with buttons downmx = e.getX();my = e.getY();showStatus( "Mouse at (" + mx + "," + my + ")" );repaint();

    e.consume();}

    public void paint( Graphics g ) {if ( isButtonPressed ) {

    g.setColor( Color.black );}else {

    g.setColor( Color.gray );}g.fillRect( mx-20, my-20, 40, 40 );

    }}

    Try clicking and dragging on the resulting applet. Notice how the status bar in your

    web browser displays the current mouse position -- that's due to the calls to

    showStatus(). (You might see some occasional flickering in this applet. This

    problem will be addressed in an upcoming lesson.)

    The MouseEvent data that gets passed into each of the mouse*() functions contains

    information on the position of the mouse, the state of the mouse buttons and modifier

    keys (i.e. the Shift, Alt, Ctrl, and Meta keys), the time at which the event occurred,

    etc. To find out how to access this information, go here.

    Another example:

    http://java.sun.com/products/jdk/1.3/docs/api/java/awt/event/MouseEvent.htmlhttp://java.sun.com/products/jdk/1.3/docs/api/java/awt/event/MouseEvent.html
  • 8/14/2019 swet_Java Applet Tutorial

    10/30

    import java.applet.*;import java.awt.*;import java.awt.event.*;

    public class Mouse2 extends Appletimplements MouseListener, MouseMotionListener {

    int width, height;int x, y; // the coordinates of the upper-left corner of the

    boxint mx, my; // the most recently recorded mouse coordinatesboolean isMouseDraggingBox = false;

    public void init() {width = getSize().width;height = getSize().height;setBackground( Color.black );

    x = width/2 - 20;y = height/2 - 20;

    addMouseListener( this );addMouseMotionListener( this );

    }

    public void mouseEntered( MouseEvent e ) { }public void mouseExited( MouseEvent e ) { }public void mouseClicked( MouseEvent e ) { }public void mousePressed( MouseEvent e ) {

    mx = e.getX();my = e.getY();if ( x < mx && mx < x+40 && y < my && my < y+40 ) {

    isMouseDraggingBox = true;}e.consume();

    }public void mouseReleased( MouseEvent e ) {

    isMouseDraggingBox = false;e.consume();

    }public void mouseMoved( MouseEvent e ) { }public void mouseDragged( MouseEvent e ) {

    if ( isMouseDraggingBox ) {// get the latest mouse positionint new_mx = e.getX();int new_my = e.getY();

    // displace the box by the distance the mouse moved sincethe last event

    // Note that "x += ...;" is just shorthand for "x = x +...;"

    x += new_mx - mx;y += new_my - my;

    // update our datamx = new_mx;my = new_my;

    repaint();e.consume();

    }}

    public void paint( Graphics g ) {g.setColor( Color.gray );g.fillRect( x, y, 40, 40 );

  • 8/14/2019 swet_Java Applet Tutorial

    11/30

    }}

    Try clicking and dragging on the gray square:

    A third example:

    import java.applet.*;import java.awt.*;import java.awt.event.*;import java.util.*;

    public class Mouse3 extends Appletimplements MouseListener, MouseMotionListener {

    int width, height;

    // We need a place to store a list of mouse positions.// Rather than use an array, we'll use a Vector, because

    // it allows elements to be easily appended and deleted.// (Technically, it would probably be more appropriate to// use a LinkedList, but they're only supported by Java 1.2)Vector listOfPositions;

    public void init() {width = getSize().width;height = getSize().height;setBackground( Color.black );

    listOfPositions = new Vector();

    addMouseListener( this );addMouseMotionListener( this );

    }

    public void mouseEntered( MouseEvent e ) { }public void mouseExited( MouseEvent e ) { }public void mouseClicked( MouseEvent e ) { }public void mousePressed( MouseEvent e ) { }public void mouseReleased( MouseEvent e ) { }public void mouseMoved( MouseEvent e ) {

    if ( listOfPositions.size() >= 50 ) {// delete the first element in the listlistOfPositions.removeElementAt( 0 );

    }

    // add the new position to the end of the listlistOfPositions.addElement( new Point( e.getX(), e.getY() ) );

    repaint();e.consume();

    }public void mouseDragged( MouseEvent e ) { }

    public void paint( Graphics g ) {g.setColor( Color.white );for ( int j = 1; j < listOfPositions.size(); ++j ) {

    Point A = (Point)(listOfPositions.elementAt(j-1));Point B = (Point)(listOfPositions.elementAt(j));g.drawLine( A.x, A.y, B.x, B.y );

    }}

    }

  • 8/14/2019 swet_Java Applet Tutorial

    12/30

    Move freely over the applet. Notice that moving faster makes the line stretch out

    longer.

    Exercise 5: Keyboard Input

    The source code:

    import java.applet.*;import java.awt.*;import java.awt.event.*;

    public class Keyboard1 extends Appletimplements KeyListener, MouseListener {

    int width, height;int x, y;String s = "";

    public void init() {width = getSize().width;height = getSize().height;setBackground( Color.black );

    x = width/2;y = height/2;

    addKeyListener( this );addMouseListener( this );

    }

    public void keyPressed( KeyEvent e ) { }public void keyReleased( KeyEvent e ) { }public void keyTyped( KeyEvent e ) {

    char c = e.getKeyChar();if ( c != KeyEvent.CHAR_UNDEFINED ) {

    s = s + c;repaint();e.consume();

    }}

    public void mouseEntered( MouseEvent e ) { }public void mouseExited( MouseEvent e ) { }public void mousePressed( MouseEvent e ) { }public void mouseReleased( MouseEvent e ) { }public void mouseClicked( MouseEvent e ) {

    x = e.getX();y = e.getY();s = "";repaint();e.consume();

    }

    public void paint( Graphics g ) {g.setColor( Color.gray );g.drawLine( x, y, x, y-10 );g.drawLine( x, y, x+10, y );g.setColor( Color.green );g.drawString( s, x, y );

  • 8/14/2019 swet_Java Applet Tutorial

    13/30

    }}

    Try clicking and typing into the applet. You'll probably have to click at least once

    before you begin typing, to give the applet the keyboard focus.

    Go here for more information.

    Here's a second applet that nicely integrates most of what we've learned so far.

    import java.applet.*;import java.awt.*;import java.awt.event.*;import java.util.Vector;

    public class Keyboard2 extends Appletimplements KeyListener, MouseListener, MouseMotionListener {

    int width, height;int N = 25;Color[] spectrum;Vector listOfPositions;String s = "";int skip = 0;

    public void init() {width = getSize().width;height = getSize().height;setBackground( Color.black );

    spectrum = new Color[ N ];for ( int i = 0; i < N; ++i ) {

    spectrum[i] = new Color( Color.HSBtoRGB(i/(float)N,1,1) );}

    listOfPositions = new Vector();

    addKeyListener( this );addMouseListener( this );addMouseMotionListener( this );

    }

    public void keyPressed( KeyEvent e ) { }public void keyReleased( KeyEvent e ) { }public void keyTyped( KeyEvent e ) {

    char c = e.getKeyChar();

    if ( c != KeyEvent.CHAR_UNDEFINED ) {s = s + c;repaint();e.consume();

    }}

    public void mouseEntered( MouseEvent e ) { }public void mouseExited( MouseEvent e ) { }public void mouseClicked( MouseEvent e ) {

    s = "";repaint();e.consume();

    }

    public void mousePressed( MouseEvent e ) { }public void mouseReleased( MouseEvent e ) { }public void mouseMoved( MouseEvent e ) {

    http://java.sun.com/products/jdk/1.3/docs/api/java/awt/event/KeyEvent.htmlhttp://java.sun.com/products/jdk/1.3/docs/api/java/awt/event/KeyEvent.html
  • 8/14/2019 swet_Java Applet Tutorial

    14/30

    // only process every 5th mouse eventif ( skip > 0 ) {

    -- skip; // this is shorthand for "skip = skip-1;"return;

    }else skip = 5;

    if ( listOfPositions.size() >= N ) {// delete the first element in the listlistOfPositions.removeElementAt( 0 );

    }

    // add the new position to the end of the listlistOfPositions.addElement( new Point( e.getX(), e.getY() ) );

    repaint();e.consume();

    }public void mouseDragged( MouseEvent e ) { }

    public void paint( Graphics g ) {if ( s != "" ) {

    for ( int j = 0; j < listOfPositions.size(); ++j ) {g.setColor( spectrum[ j ] );Point p = (Point)(listOfPositions.elementAt(j));g.drawString( s, p.x, p.y );

    }}

    }}

    Click, type, and move the mouse. You might see some flickering. Depending on the

    speed of your computer, you might also find that the mouse position is being sampled

    too quickly or too slowly. The upcoming lessons will give you tools to fix both of

    these problems.

    Exercise 6: Threads and Animation

    The only functions we have seen in applets so far are init(), paint(), and functions

    called in response to input events. All of these functions are supposed to do a small

    amount of work and return quickly. There has been no opportunity, so far, for a

    function to loop and do some continuous work.

    This applet creates a thread, a separate stream of execution, to perform a background

    task. The body of the thread's code is in the run() function. In this case, the purpose

    of the thread is to increment the variable i once every 1000 milliseconds, and cause

    the applet to redraw itself. The result is a simple animation.

    import java.applet.*;import java.awt.*;

    public class Threads1 extends Applet implements Runnable {

    int width, height;int i = 0;

    Thread t = null;boolean threadSuspended;

  • 8/14/2019 swet_Java Applet Tutorial

    15/30

    // Executed when the applet is first created.public void init() {

    System.out.println("init(): begin");width = getSize().width;height = getSize().height;setBackground( Color.black );

    System.out.println("init(): end");}

    // Executed when the applet is destroyed.public void destroy() {

    System.out.println("destroy()");}

    // Executed after the applet is created; and also whenever// the browser returns to the page containing the applet.public void start() {

    System.out.println("start(): begin");if ( t == null ) {

    System.out.println("start(): creating thread");

    t = new Thread( this );System.out.println("start(): starting thread");threadSuspended = false;t.start();

    }else {

    if ( threadSuspended ) {threadSuspended = false;System.out.println("start(): notifying thread");synchronized( this ) {

    notify();}

    }}

    System.out.println("start(): end");}

    // Executed whenever the browser leaves the page containing theapplet.

    public void stop() {System.out.println("stop(): begin");threadSuspended = true;

    }

    // Executed within the thread that this applet created.public void run() {

    System.out.println("run(): begin");try {

    while (true) {System.out.println("run(): awake");

    // Here's where the thread does some work++i; // this is shorthand for "i = i+1;"if ( i == 10 ) {

    i = 0;}showStatus( "i is " + i );

    // Now the thread checks to see if it should suspenditself

    if ( threadSuspended ) {synchronized( this ) {

    while ( threadSuspended ) {System.out.println("run(): waiting");wait();

  • 8/14/2019 swet_Java Applet Tutorial

    16/30

    }}

    }System.out.println("run(): requesting repaint");repaint();System.out.println("run(): sleeping");t.sleep( 1000 ); // interval given in milliseconds

    }}catch (InterruptedException e) { }System.out.println("run(): end");

    }

    // Executed whenever the applet is asked to redraw itself.public void paint( Graphics g ) {

    System.out.println("paint()");g.setColor( Color.green );g.drawLine( width, height, i * width / 10, 0 );

    }}

    The resulting applet:

    The call to showStatus() in run() will cause the value ofi to appear in the

    browser's status bar. If you open the Java Console of your browser (in Netscape 4.7,

    this is accessible under the Communicator|Tools submenu), you'll see the text printed

    by calls to System.out.println() .

    Unfortunately, the source code is complicated because the applet is supposed to

    suspend execution of the thread whenever the browser leaves the web page containing

    the applet, and resume execution upon return. This is done in the stop() and start()functions, respectively. Basically, the thread monitors the value of some variable, here

    called threadSuspended, that behaves like a flag. When the thread sees that it is

    supposed to suspend itself, it calls wait(), which blocks the thread and does not

    allow it to continue executing until the applet calls notify().

    Strictly speaking, it is not necessary to suspend the thread at all, but failing to do so is

    somewhat irresponsible. The user's CPU could become bogged down with useless

    instructions to execute long after the browser has left the page containing the applet.

    Those tempted to forgo "proper" coding to make their applets simpler can use this as

    an example. When you run this applet, open the Java Console of your browser, and

    then leave the page the applet is on. Notice how messages continue to be printed outin the console, and the value ofi continues to be displayed in the status bar,

    demonstrating that the thread is still running in the background.

    For more information on threads, try here, here and here.

    Exercise 7: Backbuffers

    Up to this point, the graphics drawn by our applets have been relatively simple. Withmore complex graphics however, whether in animations or interactive programs,

    http://www.dgp.toronto.edu/~mjmcguff/learn/java/06-threads/Threads2.javahttp://java.sun.com/products/jdk/1.3/docs/api/java/lang/Thread.htmlhttp://java.sun.com/products/jdk/1.3/docs/api/java/lang/Object.html#notify%28%29http://java.sun.com/products/jdk/1.3/docs/guide/misc/threadPrimitiveDeprecation.htmlhttp://java.sun.com/products/jdk/1.3/docs/guide/misc/threadPrimitiveDeprecation.htmlhttp://java.sun.com/products/jdk/1.3/docs/api/java/lang/Object.html#notify%28%29http://java.sun.com/products/jdk/1.3/docs/api/java/lang/Thread.htmlhttp://www.dgp.toronto.edu/~mjmcguff/learn/java/06-threads/Threads2.java
  • 8/14/2019 swet_Java Applet Tutorial

    17/30

    flicker can become a problem. (You may have already noticed subtle flickering in

    some of the previous applets.)

    This example demonstrate the problem. It uses a pseudo-random number generator to

    produce a big, hairy tangle of lines. The lines follow the mouse cursor.

    import java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;

    public class NoBackbuffer1 extends Appletimplements MouseMotionListener {

    int width, height;int mx, my; // the mouse coordinatesPoint[] points;int N = 300;

    public void init() {

    width = getSize().width;height = getSize().height;setBackground( Color.black );

    mx = width/2;my = height/2;

    points = new Point[ N ];for ( int i = 0; i < N; ++i ) {

    int x = (int)(( Math.random() - 0.5 ) * width / 1.5);int y = (int)(( Math.random() - 0.5 ) * height / 1.5);points[i] = new Point( x, y );

    }

    addMouseMotionListener( this );}

    public void mouseMoved( MouseEvent e ) {mx = e.getX();my = e.getY();showStatus( "Mouse at (" + mx + "," + my + ")" );repaint();e.consume();

    }public void mouseDragged( MouseEvent e ) { }

    public void paint( Graphics g ) {g.setColor( Color.white );

    for ( int j = 1; j < N; ++j ) {Point A = points[j-1];Point B = points[j];g.drawLine( mx+A.x, my+A.y, mx+B.x, my+B.y );

    }}

    }

    The output:

    You probably see flickering when you move the mouse over the applet. The lines take

    a significant amount of time to draw, and since the canvas is cleared before eachredraw, the image on the canvas is actually incomplete most of the time.

  • 8/14/2019 swet_Java Applet Tutorial

    18/30

    This second example makes the problem even more pronounced by rendering a

    bitmap image in the background.

    import java.applet.*;import java.awt.*;import java.awt.event.*;

    import java.lang.Math;

    public class NoBackbuffer2 extends Appletimplements MouseMotionListener {

    int width, height;int mx, my; // the mouse coordinatesPoint[] points;int N = 300;Image img;

    public void init() {width = getSize().width;height = getSize().height;

    setBackground( Color.black );

    mx = width/2;my = height/2;

    points = new Point[ N ];for ( int i = 0; i < N; ++i ) {

    int x = (int)(( Math.random() - 0.5 ) * width / 1.5);int y = (int)(( Math.random() - 0.5 ) * height / 1.5);points[i] = new Point( x, y );

    }

    // Download the image "fractal.gif" from the// same directory that the applet resides in.

    img = getImage( getDocumentBase(), "fractal.gif" );

    addMouseMotionListener( this );}

    public void mouseMoved( MouseEvent e ) {mx = e.getX();my = e.getY();showStatus( "Mouse at (" + mx + "," + my + ")" );repaint();e.consume();

    }public void mouseDragged( MouseEvent e ) { }

    public void paint( Graphics g ) {g.drawImage( img, 0, 0, this );g.setColor( Color.white );for ( int j = 1; j < N; ++j ) {

    Point A = points[j-1];Point B = points[j];g.drawLine( mx+A.x, my+A.y, mx+B.x, my+B.y );

    }}

    }

    The output:

    The flickering you see now should be especially bad.

  • 8/14/2019 swet_Java Applet Tutorial

    19/30

  • 8/14/2019 swet_Java Applet Tutorial

    20/30

    }

    repaint();e.consume();

    }public void mouseDragged( MouseEvent e ) { }

    public void paint( Graphics g ) {g.drawImage( backbuffer, 0, 0, this );

    }}

    The output:

    Why do we still see flicker ? Whenever the applet is supposed to redraw itself, the

    applet's update() function gets called. The java.awt.Component class (which is a

    base class ofApplet) defines a default version ofupdate() which does the

    following: (1) clears the applet by filling it with the background color, (2) sets thecolor of the graphics context to be the applet's foreground color, (3) calls the applet's

    paint() function. We see flickering because the canvas is still cleared before each

    redraw. To prevent this, we need to define our own update() function, to override the

    base class' behavior.

    import java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;

    public class Backbuffer2 extends Appletimplements MouseMotionListener {

    int width, height;int mx, my; // the mouse coordinatesPoint[] points;int N = 300;Image img;Image backbuffer;Graphics backg;

    public void init() {width = getSize().width;height = getSize().height;

    mx = width/2;my = height/2;

    points = new Point[ N ];for ( int i = 0; i < N; ++i ) {

    int x = (int)(( Math.random() - 0.5 ) *

    Exercise 8: Painting

    In addition to reducing flicker, a backbuffer can be used to store the accumulated

    results of drawing operations. We can easily implement a canvas-and-brush applet:

    import java.applet.*;import java.awt.*;

    http://java.sun.com/products/jdk/1.3/docs/api/java/awt/Component.html#update%28java.awt.Graphics%29http://java.sun.com/products/jdk/1.3/docs/api/java/awt/Component.html#update%28java.awt.Graphics%29http://java.sun.com/products/jdk/1.3/docs/api/java/awt/Component.html#update%28java.awt.Graphics%29
  • 8/14/2019 swet_Java Applet Tutorial

    21/30

    import java.awt.event.*;

    public class Brush1 extends Appletimplements MouseMotionListener {

    int width, height;Image backbuffer;

    Graphics backg;

    public void init() {width = getSize().width;height = getSize().height;

    backbuffer = createImage( width, height );backg = backbuffer.getGraphics();backg.setColor( Color.black );backg.fillRect( 0, 0, width, height );backg.setColor( Color.white );

    addMouseMotionListener( this );}

    public void mouseMoved( MouseEvent e ) { }public void mouseDragged( MouseEvent e ) {

    int x = e.getX();int y = e.getY();backg.fillOval(x-5,y-5,10,10);repaint();e.consume();

    }

    public void update( Graphics g ) {g.drawImage( backbuffer, 0, 0, this );

    }

    public void paint( Graphics g ) {update( g );

    }}

    Click and drag over the applet to paint:

    Another example:

    import java.applet.*;import java.awt.*;import java.awt.event.*;

    public class Keyboard3 extends Appletimplements KeyListener, MouseListener {

    int width, height;int x, y;String s = "";Image backbuffer;Graphics backg;

    public void init() {width = getSize().width;height = getSize().height;setBackground( Color.black );

    x = width/2;y = height/2;

  • 8/14/2019 swet_Java Applet Tutorial

    22/30

    backbuffer = createImage( width, height );backg = backbuffer.getGraphics();backg.setColor( Color.black );backg.fillRect( 0, 0, width, height );backg.setColor( Color.green );

    addKeyListener( this );addMouseListener( this );

    }

    public void keyPressed( KeyEvent e ) { }public void keyReleased( KeyEvent e ) { }public void keyTyped( KeyEvent e ) {

    char c = e.getKeyChar();if ( c != KeyEvent.CHAR_UNDEFINED ) {

    s = s + c;backg.drawString( s, x, y );repaint();e.consume();

    }

    }

    public void mouseEntered( MouseEvent e ) { }public void mouseExited( MouseEvent e ) { }public void mousePressed( MouseEvent e ) { }public void mouseReleased( MouseEvent e ) { }public void mouseClicked( MouseEvent e ) {

    x = e.getX();y = e.getY();s = "";repaint();e.consume();

    }

    public void update( Graphics g ) {g.drawImage( backbuffer, 0, 0, this );g.setColor( Color.gray );g.drawLine( x, y, x, y-10 );g.drawLine( x, y, x+10, y );

    }

    public void paint( Graphics g ) {update( g );

    }}

    Click and type; click again and type some more:

    A third example:

    import java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;

    public class Brush2 extends Appletimplements MouseMotionListener {

    int width, height;Image backbuffer;

    Graphics backg;

    int mx, my;

  • 8/14/2019 swet_Java Applet Tutorial

    23/30

    double t = 0;

    public void init() {width = getSize().width;height = getSize().height;

    mx = width / 2;my = height / 2;

    backbuffer = createImage( width, height );backg = backbuffer.getGraphics();backg.setColor( Color.black );backg.fillRect( 0, 0, width, height );backg.setColor( Color.white );

    addMouseMotionListener( this );}

    public void mouseMoved( MouseEvent e ) { }public void mouseDragged( MouseEvent e ) {

    int x = e.getX();int y = e.getY();int dx = x - mx;int dy = y - my;t += Math.sqrt( dx*dx + dy*dy ) / 20;if ( t > 2*Math.PI ) {

    t -= 2*Math.PI;}backg.drawLine( x, y, x+(int)(15*Math.cos(t)),

    y+(int)(15*Math.sin(t)) );mx = x;my = y;repaint();e.consume();

    }

    public void update( Graphics g ) {g.drawImage( backbuffer, 0, 0, this );

    }

    public void paint( Graphics g ) {update( g );

    }}

    Programming a custom brush and canvas enables experimentation with behaviors not

    otherwise possible. An understanding of arithmetic, geometry, and trigonometry will

    enhance your own ability to "play" in this medium.

    Exercise 9: Clocks

    The source code:

    import java.applet.*;import java.awt.*;import java.util.*;

    import java.text.*;

    public class Clock1 extends Applet implements Runnable {

  • 8/14/2019 swet_Java Applet Tutorial

    24/30

    int width, height;Thread t = null;boolean threadSuspended;int hours=0, minutes=0, seconds=0;String timeString = "";

    public void init() {width = getSize().width;height = getSize().height;setBackground( Color.black );

    }

    public void start() {if ( t == null ) {

    t = new Thread( this );t.setPriority( Thread.MIN_PRIORITY );threadSuspended = false;t.start();

    }else {

    if ( threadSuspended ) {threadSuspended = false;synchronized( this ) {

    notify();}

    }}

    }

    public void stop() {threadSuspended = true;

    }

    public void run() {

    try {while (true) {

    // Here's where the thread does some workCalendar cal = Calendar.getInstance();hours = cal.get( Calendar.HOUR_OF_DAY );if ( hours > 12 ) hours -= 12;minutes = cal.get( Calendar.MINUTE );seconds = cal.get( Calendar.SECOND );

    SimpleDateFormat formatter= new SimpleDateFormat( "hh:mm:ss",

    Locale.getDefault() );Date date = cal.getTime();

    timeString = formatter.format( date );

    // Now the thread checks to see if it should suspenditself

    if ( threadSuspended ) {synchronized( this ) {

    while ( threadSuspended ) {wait();

    }}

    }repaint();t.sleep( 1000 ); // interval given in milliseconds

    }

    }catch (InterruptedException e) { }

    }

  • 8/14/2019 swet_Java Applet Tutorial

    25/30

    void drawHand( double angle, int radius, Graphics g ) {angle -= 0.5 * Math.PI;int x = (int)( radius*Math.cos(angle) );int y = (int)( radius*Math.sin(angle) );g.drawLine( width/2, height/2, width/2 + x, height/2 + y );

    }

    void drawWedge( double angle, int radius, Graphics g ) {angle -= 0.5 * Math.PI;int x = (int)( radius*Math.cos(angle) );int y = (int)( radius*Math.sin(angle) );angle += 2*Math.PI/3;int x2 = (int)( 5*Math.cos(angle) );int y2 = (int)( 5*Math.sin(angle) );angle += 2*Math.PI/3;int x3 = (int)( 5*Math.cos(angle) );int y3 = (int)( 5*Math.sin(angle) );g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y

    );g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y

    );g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 +

    y3 );}

    public void paint( Graphics g ) {g.setColor( Color.gray );drawWedge( 2*Math.PI * hours / 12, width/5, g );drawWedge( 2*Math.PI * minutes / 60, width/3, g );drawHand( 2*Math.PI * seconds / 60, width/2, g );g.setColor( Color.white );g.drawString( timeString, 10, height-10 );

    }}

    The resulting applet:

    Note that the time displayed in the lower left corner may not be correct -- certain

    browsers (perhaps only older versions?) seem to interpret the "default" time zone as

    something different from the local time zone. (The hands, however, always seem to

    display the correct time.) If this problem bothers you, try using

    timeString = date.toString();

    instead of

    timeString = formatter.format( date );

    Exercise 10: Playing with Text

  • 8/14/2019 swet_Java Applet Tutorial

    26/30

    under construction ...

    Font font = new Font( "Monospaced", Font.PLAIN, 12 );

    Graphics g;

    g.setFont( font );

    FontMetrics fm = getFontMetrics( font );

    int charWidth = fm.charWidth('W');int charHeight = fm.getHeight();

    String s = "whatever";int stringWidth = fm.stringWidth( s );

    Exercise 11: 3D Graphics

    The source code:

    import java.applet.*;import java.awt.*;import java.awt.event.*;import java.lang.Math;

    class Point3D {public int x, y, z;public Point3D( int X, int Y, int Z ) {

    x = X; y = Y; z = Z;}

    }

    class Edge {public int a, b;public Edge( int A, int B ) {

    a = A; b = B;}

    }

    public class WireframeViewer extends Appletimplements MouseListener, MouseMotionListener {

    int width, height;int mx, my; // the most recently recorded mouse coordinates

    Image backbuffer;Graphics backg;

    int azimuth = 35, elevation = 30;

    Point3D[] vertices;Edge[] edges;

    public void init() {width = getSize().width;height = getSize().height;

    vertices = new Point3D[ 8 ];vertices[0] = new Point3D( -1, -1, -1 );vertices[1] = new Point3D( -1, -1, 1 );vertices[2] = new Point3D( -1, 1, -1 );

  • 8/14/2019 swet_Java Applet Tutorial

    27/30

    vertices[3] = new Point3D( -1, 1, 1 );vertices[4] = new Point3D( 1, -1, -1 );vertices[5] = new Point3D( 1, -1, 1 );vertices[6] = new Point3D( 1, 1, -1 );vertices[7] = new Point3D( 1, 1, 1 );

    edges = new Edge[ 12 ];

    edges[ 0] = new Edge( 0, 1 );edges[ 1] = new Edge( 0, 2 );edges[ 2] = new Edge( 0, 4 );edges[ 3] = new Edge( 1, 3 );edges[ 4] = new Edge( 1, 5 );edges[ 5] = new Edge( 2, 3 );edges[ 6] = new Edge( 2, 6 );edges[ 7] = new Edge( 3, 7 );edges[ 8] = new Edge( 4, 5 );edges[ 9] = new Edge( 4, 6 );edges[10] = new Edge( 5, 7 );edges[11] = new Edge( 6, 7 );

    backbuffer = createImage( width, height );

    backg = backbuffer.getGraphics();drawWireframe( backg );

    addMouseListener( this );addMouseMotionListener( this );

    }

    void drawWireframe( Graphics g ) {

    // compute coefficients for the projectiondouble theta = Math.PI * azimuth / 180.0;double phi = Math.PI * elevation / 180.0;float cosT = (float)Math.cos( theta ), sinT = (float)Math.sin(

    theta );

    float cosP = (float)Math.cos( phi ), sinP = (float)Math.sin(phi );

    float cosTcosP = cosT*cosP, cosTsinP = cosT*sinP,sinTcosP = sinT*cosP, sinTsinP = sinT*sinP;

    // project vertices onto the 2D viewportPoint[] points;points = new Point[ vertices.length ];int j;int scaleFactor = width/4;float near = 3; // distance from eye to near planefloat nearToObj = 1.5f; // distance from near plane to center

    of objectfor ( j = 0; j < vertices.length; ++j ) {

    int x0 = vertices[j].x;int y0 = vertices[j].y;int z0 = vertices[j].z;

    // compute an orthographic projectionfloat x1 = cosT*x0 + sinT*z0;float y1 = -sinTsinP*x0 + cosP*y0 + cosTsinP*z0;

    // now adjust things to get a perspective projectionfloat z1 = cosTcosP*z0 - sinTcosP*x0 - sinP*y0;x1 = x1*near/(z1+near+nearToObj);y1 = y1*near/(z1+near+nearToObj);

    // the 0.5 is to round off when converting to int

    points[j] = new Point((int)(width/2 + scaleFactor*x1 + 0.5),(int)(height/2 - scaleFactor*y1 + 0.5)

  • 8/14/2019 swet_Java Applet Tutorial

    28/30

    );}

    // draw the wireframeg.setColor( Color.black );g.fillRect( 0, 0, width, height );g.setColor( Color.white );

    for ( j = 0; j < edges.length; ++j ) {g.drawLine(

    points[ edges[j].a ].x, points[ edges[j].a ].y,points[ edges[j].b ].x, points[ edges[j].b ].y

    );}

    }

    public void mouseEntered( MouseEvent e ) { }public void mouseExited( MouseEvent e ) { }public void mouseClicked( MouseEvent e ) { }public void mousePressed( MouseEvent e ) {

    mx = e.getX();my = e.getY();

    e.consume();}public void mouseReleased( MouseEvent e ) { }public void mouseMoved( MouseEvent e ) { }public void mouseDragged( MouseEvent e ) {

    // get the latest mouse positionint new_mx = e.getX();int new_my = e.getY();

    // adjust angles according to the distance travelled by themouse

    // since the last eventazimuth -= new_mx - mx;elevation += new_my - my;

    // update the backbufferdrawWireframe( backg );

    // update our datamx = new_mx;my = new_my;

    repaint();e.consume();

    }

    public void update( Graphics g ) {g.drawImage( backbuffer, 0, 0, this );

    showStatus("Elev: "+elevation+" deg, Azim: "+azimuth+" deg");}

    public void paint( Graphics g ) {update( g );

    }}

    Notice that the compiler generates 3 .class files: one for each of the classes defined.

    Click and drag on the applet to rotate the cube.

  • 8/14/2019 swet_Java Applet Tutorial

    29/30

    Exercise 12: Odds and Ends

    Audio

    To play audio files, use Applet.play(). Java 1.1 only supports Sun Audio (.au)

    files, or specifically, 8 bit, u-law, 8000 Hz, one-channel Sun format. BothApplet.play() and AudioClip.play() are non-blocking: they return immediately

    after starting the playback of the audio file. Try here for an example.

    Applet Info

    You can embed information about your applet inside itself by defining

    getAppletInfo() and getParameterInfo() .

    Debugging Tips

    If you're having trouble understanding what your applet is doing (or not doing), use

    System.out.println() and showStatus() to print out the values of variables and

    information about where the program is.

    Browsers won't normally reload applets after they've been loaded once. If you test an

    applet inside your browser, and then modify the applet's source code and recompile,

    simply reloading the webpage in your browser isn't enough to view the new applet.

    You'll have to exit and restart your browser. To avoid this nuisance, do initial testing

    of applets with appletviewer rather than a web browser.

    Conditional Compilation

    In C, blocks of code can be conditionally compiled using #define flags thus:#define FLAG 1...#ifdef FLAG...#else...#endif

    Java is not as flexible, but allows for something that is sometimes just as good:

    private static final boolean DEBUG = false;...if ( DEBUG ) {

    ...}else {

    ...}

    The final keyword means the variable is constant, so unless your compiler's

    optimizer is brain-dead, it should prune out the conditional and the unreachable block

    of code.

    http://www.dgp.toronto.edu/~mjmcguff/learn/java/12-miscellaneous/audioTest.htmlhttp://java.sun.com/products/jdk/1.3/docs/api/java/applet/Applet.html#getAppletInfo%28%29http://java.sun.com/products/jdk/1.3/docs/api/java/applet/Applet.html#getParameterInfo%28%29http://java.sun.com/products/jdk/1.3/docs/api/java/applet/Applet.html#getParameterInfo%28%29http://java.sun.com/products/jdk/1.3/docs/api/java/applet/Applet.html#getAppletInfo%28%29http://www.dgp.toronto.edu/~mjmcguff/learn/java/12-miscellaneous/audioTest.html
  • 8/14/2019 swet_Java Applet Tutorial

    30/30

    import java.applet.*;

    import java.awt.*;import java.lang.Math;

    public class ArchimedianSpiral extends Applet {

    int width, height;int N = 30; // number of points per full rotationint W = 5; // winding number, or number of full rotations

    public void init() {

    width = getSize().width;height = getSize().height;setBackground( Color.black );setForeground( Color.green );

    }

    public void paint( Graphics g ) {

    int x1 = 0, y1 = 0, x2, y2;for ( int i = 1; i


Recommended