Introduction to Computer Graphics and Java Programming for Artists


School of the Museum of Fine Arts ::: Continuing Education

George Aroush, instructor


Lecture Three -- The World Wide Web; Loops & Controls: Part I; Simple Animation


 

Readings

  1. The handouts named:
  2. Sample Programs in Batch Three:
  3. "Java How to Program" by Paul J. Deitel, and Harvey M. Deitel

 

Exercises

    Do before our next lecture

  1. Write a program with a while loop that counts down from 10 to 1 using drawString() and a variable to print the counts down. (Re-write the While.java demo in the while Loops section so that the demo runs in a browser as an Applet)
  2. Re-write the BounceOne.java demo program to make the square fall from the "ceiling" of the screen and bounce off the "floor".
  3. Re-write BounceTwo.java or BounceThree.java demo program to make the shape move in a path that makes it bounce off all four sides of the screen, like a pool ball.

Back to the top of this page. Back to main Index

 

The World Wide Web

The Internet

The Internet began in the late 1960s as an experiment in the design of robust computer networks. The goal was to construct a network of computers that could withstand the loss of several machines without compromising the ability of the remaining once to communicate. Funding came from the U.S. Department of Defense, which had a vested interest in building information networks that could withstand nuclear attack.

With the advent of high-speed modems for digital communication over common phone lines, some individuals and organizations not directly tied to the main digital pipelines began connecting and taking advantage of the network's advanced and global communications. Nonetheless, it wasn't until around 1993 that the Internet really took off.

Several crucial events led to the meteoric rise in popularity of the Internet.   One of the key once happened in early 1990s when businesses and individuals pressured the larger computer networks on the mostly U.S. government-funded Internet to open their systems for nearly unrestricted traffic.

HTML and the World Wide Web

At about the same time the Internet opened up for business, some physicists at CERN, the European Particle Physics Laboratory, released an authoring language and distribution system they developed for creating and sharing multimedia-enabled, integrated electronic documents over the Internet. And soon was born Hypertext Markup Language (HTML), browser software, and the World Wide Web. No longer did authors have to distribute their work as fragmented collections of pictures, sounds, and text.  HTML unified those elements.   Moreover, the World Wide Web's systems enabled hypertext linking, whereby documents automatically referenced other documents, located anywhere around the world: less rummaging, more productive time online.

The final spike to the Internet happened when some students and faculty at the National Center for Supercomputing Applications (NCSA) at the University of Illinois, Urban-Champaign wrote a web browser called Mosaic.

The Internet Language

Every computer that's connected to the Internet has a unique address (identifier): a number whose format is defined by the Internet Protocol (IP).  An IP address is typically made up of four numbers, each less than 255, joined together by periods, such as 192.14.244.73 or 130.57.89.214. While computers and the Internet only understand numbers, people prefer names. For this reason, each computer is also given a name bestowed upon it by its owner. There are several million machines on the Net, so it would be very difficult to come up with that many unique names. Recall, though, that the Internet is a network of networks. It is divided into groups known as domains, which are further divided into one or more sub-domains. So, while we might choose a very common name for our computer, it becomes unique when we append, like surnames, all of the machine's domain names as a period-separated suffix, creating a fully qualified domain name. For example, www.smfa.edu translates to a machine named "www" that's part of the domain known as "edu", which, in turn, is part of the education (edu) branch of the Internet. Other branches are: commercial (com), organizations (org), U.S. government (gov). Computers and networks outside the U.S. have a two letter abbreviation at the end such as: "ca" for Canada, "jp" for Japan, and "uk" for the United Kingdom.

Special computers, known as name servers, keep tables of machine names and their associated unique IP numerical addresses, and translate one into the other for us and for our machines.  Domain names must be registered with the nonprofit organization InterNIC. Once registered, the owner of the domain name broadcasts it and its address to other domain name servers around the world. Each domain and sub-domain has an associated name server, so ultimately every machine is known uniquely by both a name and an IP address.

The flow of Information

The Internet connects two kinds of computers: servers, which serve up documents, images, sounds, programs, etc, and client, which retrieve and display what is in the document. A program called browsers are used on the client end to view the documents and images that the server provides. Several Web browsers are available such as: Netscape Navigator, Microsoft's Internet Explorer, NCSA Mosaic, Netcom's WebCruiser and InterCon's NetShark. By far Navigator and Internet Explorer are the most popular browsers.

Web activities normally begins on the client end. The browser begins by connecting to a server via it's name such as: www.smfa.edu which by default ends up making a request from the server to provide the client with an initial document (Web page.) This request and the server's rely is formatted according to the dictates of the HyperText Transfer Protocol (HTTP) standard. Through this protocol (communication language) data flows back and forth between the server and the client. By far the most common type of data that that the browser receives on the client end ASCII text markup using Hyper Text Markup Language (HTML.) Those days, servers also send graphical data (images), sound among other things. Browsers, deal with each type of data differently so that if it receives HTML data it will render it as text, while graphical data are rendered as images and sound data are played on the speaker. In addition to the different data types that the server can send to the browser, a browser is designed to receive binary data that is designed to be executed on the client's browser. Those executable binary data in many cases are Java programs which will be executed on the client's machine.

What is HTML?

HTML is a document-layout and hyperlink-specification language. It defines the syntax and placement of special, embedded directions that aren't displayed by the browser, but tell it how to display the contents of the document, including text, images, and other supported media. The language also tells us how to make a document interactive through special hypertext links, which connect our document with other documents.

HTML is not in any way a word processing tool, a desktop publishing solution, or even a programming language. That's because its fundamental purpose is to define the structure and appearance of documents and document families so that they might be delivered quickly and easily to  user over a network for rendering on a variety of display devices.

In short HTML is designed to structure documents and make their content more accessible, not to format documents for display purposes.


Back to the top of this page. Back to main Index.

 

while Loop

Repetition with loops

It seems like too much effort to write the same statements again and again; and plotting 10,000 points in this way would be a massive undertaking. We could save ourselves typing by using the Copy and Paste commands of the text editor (Visual J++ in this case), but that would make our program to become so huge taking up a great deal of memory in our computer. Fortunately, computers are designed to reduce human effort, and the various loop structures, which cause the computer to repeat the same group of statements any number of times, are truly labor and memory-savers. The first loop structure we will learn is the while loop, which will repeat a block of program as long as a particular relationship is true; but first we must look at Java's truth.

Truth

Java provides a rich set of operators that allow us to examine and test for conditions.   The process of checking for condition will result with either a true or a false condition. The end result of this operation is that we will be able to write programs that check and behave conditionally. Below are the list of operators that Java supports:

a == b a is equal to
a < b a is less than b
a > b a is greater than b
a <= b a is less than or equal to b
a >= b a is greater than or equal to b
a != b a is not equal to b

Every time Java sees one of these statements, it evaluates it to see if it's true or false. Java uses the keywords true and false to represent the evaluated result of the statement.

while Loops

A while loop repeats a statement or a group of statements in a block 0 or more times, as long as a given condition/expression remains true. The form of a while loop is this:

while ( expression )
    statement; 

and/or:

while ( expression )
{
    statement_1;
    statement_2;
    . . . . . .
} 

The expression is evaluated (that is checked), if it is true, statement_#s are executed. When all statement_#s are executed in the block,  expression is re-evaluated. This cycle continues until expression becomes false, at which point execution resumes after the while block/body. The While.java program below, contains a simple while loop with it's output:

/* While.java: demonstrate while loop */ 
public class While
{
    public static void main(String[] args) 
    {
        int     myNum = 10; /* declare and assign a variable */

        while (myNum > 0)   /* is 'myNum' greater then 10? */
        {
            /* yes; do the while body */
            System.out.println("'myNum' is now = " + myNum);
            myNum = myNum - 2;    /* subtract 2 form test */
        }
    }
}

Here is the output form While.java:

'myNum' is now = 10
'myNum' is now = 8
'myNum' is now = 6
'myNum' is now = 4
'myNum' is now = 2

Explanation of While.java:

while ( test-expression )
{
    loop-body
}

As the example shows, a while loop consists of the while keyword followed by a test-expression in parentheses and a loop-body. The test-expression can be any valid Java expression and is evaluated before the loop-body is executed. The loop-body can be single or compound statement and executes once every time the loop is iterated. The loop-body in While.java happens to be a statement block enclosed in braces. If the loop-body is a single statement, it can stand on its own (no braces are needed) such as:

public class While
{
    public static void main(String[] args) 
    {
        int test = 0;

        while (test > 0)
            test = test - 2;
    }
}

Another while example, which counts from 1 to 10 is given below:

public class While
{
    public static void main(String[] args) 
    {
        int count = 1;
    
        while (count <= 10)    /* expression */
        {
            System.out.print(count + "\t");  /* statement */
            count = count + 1;    /* statement */
        }
    }
}

Here is the output of this example:

1   2   3   4   5   6   7   8   9   10

(Did you note the tab inside System.out.print() method, that is the control character \t ?) Note that if we replace "<=" by "<", the last number, 10, will not be printed; (hence: the loop-body will repeat one cycle less.) Also, note that the while loop is followed by a pair of braces "{ }" just like the main() method. These are necessary only if there are more then one statement in the loop. Initially, 1 is assigned to count. As long as count is 10 or less, the loop will execute; first printing the current value of count, and then adding 1 to count. It is essential to increase the value of count, or the loop would never end.

Controlling Movement

The demo program, MovingRect.java, creates a square with the method:

java.awt.Graphics.drawRect(x, y, side, side); 

where the variable side (in this case having a value of 10) determines the size of the square. It is inside this loop:

while ( x + side < 640 )
{
    java.awt.Graphics.clearRect(0, 0, 640, 480);
    java.awt.Graphics.drawRect(x, y, side, side);
    x = x + side;
}

Since x determines where the left edge of the square is, (x + side) determines the right edge of the square. We want the loop to stop when the right side of the square crosses the right edge of the screen. This happens when (x + side) is greater than 640, or when x is greater than 630.

First the screen is cleared, to wipe out the previous image of the square (if any), then the square is drawn. Then side is added to x. Since x starts out to be equal to 0, and side is equal to 10, the loop will draw squares at x = 0, 10, 20, 30, 40, and so on, until x = 300. When x becomes 639, the right edge of the square x = side will be at 630 + 10 or 640, which is over the edge. The loop will stop executing, and the program will skip past it to the next statement.

Animation

In short, to create animation, repeat the following steps a certain number of times:

  1. draw object in present position
  2. change present position (but don't draw it yet)
  3. erase object in old position

Note that changing the X-coordinate or the Y-coordinate (if any) of the object does not actually make it move on the screen. That doesn't happen until the object is drawn on the screen with the new values of X and/or Y.


Back to the top of this page. Back to main Index

 

Making decisions

if Statement

An if statement consists of the if keyword, followed by a test expression in parentheses, and a single or compound statement (just like the while loop.) The statement is executed if the test expression is true, or skipped if the expression is false. if statement works just like the while loop except that it execute the if-body only once if the test-expression is true.

While a while loop is executing, it is often useful to test some variable inside the while loop-body to see if it has gone outside of certain limits or conditions. BounceOne.java and BounceTwo.java test the value of x to see if it is still on the screen, and reverse its direction of movement if it is not. Those two programs use a statement called an if-statement that will do something if the comparison inside its parentheses is true. BounceOne.java has the statement:

if ( x + side < 640 )
    speed = -speed; 

As soon as x is too far to the right, (x + side < 640) becomes true in the contents of the if statement, the single instruction:

speed = -speed;

is executed. This will cause the square to move to the left. If there had been more than one statement following the if, braces would be needed to enclose them. The square will appear to bounce off the right edge of the screen, and move to the left.

Compound if - and & or

Sometimes an if statement will want to test more than one relationship. Java uses && and || to join two comparisons together. && is pronounced AND; || is pronounced OR:

if ( x < 0 || x > 640 )

means: "is x less than zero OR is x greater than 620?"

if ( x > -1 && x < 640 )

means: "is x greater than -1 AND at the same time, is x less than 620?"; When using && in if or while statement, both comparisons must be true for the if or while statement to happen. When using || in if or while statement, at least one comparison must be true for the if or while statement to happen. In BounceTwo.java the following statement occurs:

if ( x < 0 || x + side > 640 )
      speed = -speed;

This says, in English, "if the square is left of the left edge or the square is right of the right edge, reverse its direction." BounceThree.java takes a different approach; using && (AND) and also offering an alternative with an else statement -- if the statement inside the " ( ) " is false, then the else part of the statement occurs instead:

if (x >= 0 && x + side <= 640) /* is this true? */
    java.awt.Graphics.drawRect(x, y, side, side); /* yes; do this line */
else
    speed = -speed; /* no; do this line */

In English, this means: "if the square is right of the left edge and left of the right edge -- it's on the screen -- then draw it, else, since it's not on the screen (reached the edge of the screen), change its direction." The else keyword is always used in conjunction with an if statement. It can form an either-or construct that executes one statement when a given expression is true and another when it is false. The Java language has no elseif keyword like some other programming languages; but it's easy to create the same effect in Java, however, since the statement that comprises an else clause can be any legal statement - including another if statement:

1.  if ( expression_1 )
2.      statement_1;
3.  else
4.      if ( expression_2 )
5.          statement_2;
6.      else
7.          statement_3;
8.
9.  statement_4;
10. statement_5;
11. . . . . .
12. . . . . . 

Here, expression_1 is evaluated; if it is true line 2 will be executed and the program will continue executing from line 8; ignoring line 3 to line 7. On the other hand if expression_1 is false, statement_1 will be ignored; instead expression_2 will be tested; if expression_2 is true, statement_2 will be executed and the program will continue executing from line 8 ignoring line 7. Finally, if expression_2 is false too, then statement_3 will be executed and the program will continue executing form line 8. Just like the while and the if statement, this example can have more then one statement in a condition if needed; we can do this by using braces " { } ". Here is the same example with more then one statement to be executed for each condition:

if ( expression )
{
    statement;
    . . . . .
}
else
{
    if ( expression )
    {
        statement;
        . . . . .
    }
    else
    {
        statement;
        . . . . .
    }
}

Back to the top of this page. Back to main Index.

 

Sample Programs -- Batch Three

MovingRect.java

/*
 *  Program:    MovingRect.java
 *  Purpose:    To demonstrate how to create a simple movement
 *  Author:     George Aroush
 *  Date:       1/1/1998
 *  Change Log: None
 *
 *  Full description of Program:
 *      Demo of while loop, in which the loop variable is used 
 *      for another purpose besides counting -- determining the 
 *      location of a rectangle.
 */

public class MovingRect extends java.applet.Applet
{
    public void paint(java.awt.Graphics g)
    {
        int     x = 0;      /* starting x-coordinate of rectangle */
        int     y = 200;    /* starting y-coordinate of rectangle */
        int     side = 10;  /* end side of square */

            /* repeat loop until x is too close */
            /* to right edge (630) of screen */
        while (x + side < 640)
        {
                /* clear screen each time for animation effect */ 
            g.clearRect(0, 0, 640, 480);

                /* draw square with side of 'side' value */ 
            g.drawRect(x, y, side, side);

            x = x + side;   /* move the square to the right */
        } 
    }
}

MovingRect.htm

<html>
<head>
<title>MovingRect</title>
</head>
<body>
    <hr>
    <applet code=MovingRect width=640 height=480></applet>
    <hr>
</body>
</html>

BounceOne.java

/*
 *  Program:    BounceOne.java
 *  Purpose:    To demonstrate how to use logic in Java
 *  Author:     George Aroush
 *  Date:       1/1/1998
 *  Change Log: None
 *
 *  Full description of Program:
 *      Demonstration of if statement; imitates square pool ball
 */

public class BounceOne extends java.applet.Applet
{
    public void paint(java.awt.Graphics g)
    {
        int     x = 0;      /* position of */
        int     y = 200;    /* square */
        int     side;       /* size of square */
        int     xSpeed;     /* speed of square */
        int     count = 0;  /* counts loops */

        xSpeed = side = 10;     /* square will move a distance equal to its side */

        while (count < 126)     /* giving us 126 frames/movement */
        {
            g.clearRect(0, 0, 640, 480);    /* erase old square */
            
            g.drawRect(x, y, side, side);   /* draw new square */

            x = x + xSpeed;     /* move the square */

            if (x + side > 639)     /* is square at right edge? */
                xSpeed = -xSpeed;   /* yes; reverse direction */

            count = count + 1;
        }
    }
}

BounceOne.htm

<html>
<head>
<title>BounceOne</title>
</head>
<body>
    <hr>
    <applet code=BounceOne width=640 height=480></applet>
    <hr>
</body>
</html>

BounceTwo.java

/*
 *  Program:    BounceTwo.java
 *  Purpose:    To demonstrate how to use logic in Java
 *  Author:     George Aroush
 *  Date:       1/1/1998
 *  Change Log: None
 *
 *  Full description of Program:
 *      Now the square bounces off both edges shows the "if" 
 *      statement with either/or conditions
 */

public class BounceTwo extends java.applet.Applet
{
    public void paint(java.awt.Graphics g)
    {
        int     x = 0;          /* position of square */
        int     y = 200;
        int     xSpeed, side;   /* square's speed and size */
        int     count = 0;      /* to count frames */

        xSpeed = 6;     /* a slower but larger square than in BounceOne.java */
        side = 30;      /* the size of the square */ 

        while (count < 1000)     /* 1000 frames */
        {
            g.clearRect(0, 0, 640, 480); 

            if (x < 0 || x + side > 610)    /* crossed left OR right edge? */
                xSpeed = -xSpeed;           /* yes; then reverse direction */

            x = x + xSpeed;     /* move the square */

            g.drawRect(x, y, side, side);

            count = count + 1;      /* loop counter */
        }
    }
}

BounceTwo.htm

<html>
<head>
<title>BounceTwo</title>
</head>
<body>
    <hr>
    <applet code=BounceTwo width=640 height=480></applet>
    <hr>
</body>
</html>

BounceThree.java

/*
 *  Program:    BounceThree.java
 *  Purpose:    To demonstrate how to use logic in Java
 *  Author:     George Aroush
 *  Date:       1/1/1998
 *  Change Log: None
 *
 *  Full description of Program:
 *      Another bouncing square -- shows "if .. else" and "&&" 
 *      (AND) operation 
 */

public class BounceThree extends java.applet.Applet
{
    public void paint(java.awt.Graphics g)
    {
        int     x = 0;
        int     y = 200;
        int     speed, side;
        int     count = 0;

        speed = 2;  /* a little, slow square */
        side = 5;   /* size of square */ 

        while (count < 10000)
        {
            g.clearRect(0, 0, 640, 480); 

                /* draw the square only if it is on the screen */
                /* if it is 'true' that x is to the right of */
                /* the left AND is at least the square's size */
                /* away from the right edge */ 

            if (x >= 0 && x <= 639 - side)      /* check to see where is the square */
                g.drawRect(x, y, side, side);   /* draw the square if it is on the screen */
            else                                /* otherwise it must have hit the edge */
                speed = -speed;                 /* reverse direction, without drawing yet */ 
        
            x = x + speed;      /* move the square */ 
        
            count = count + 1; 
        }
    }
}

BounceThree.htm

<html>
<head>
<title>BounceThree</title>
</head>
<body>
    <hr>
    <applet code=BounceThree width=640 height=480></applet>
    <hr>
</body>
</html>

Back to the top of this page. Back to main Index.