INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM

ICS102, SECTIONS 65  (002 Semester)

INTRODUCTION TO COMPUTING

LAB  #04 Introduction to Applets

Instructor: Bashir M. Ghandi

 


Objectives:

To gain experience with:

 

1.  Steps involved in writing an applet

·         Write the applet program , save and compile as usual (same as applications)

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Graphics2D;

 

public class HelloApplet extends Applet {

      public void paint(Graphics g) {

            Graphics2D g2 = (Graphics2D) g;

            g2.drawString("Hello  World", 50, 25);

      }

}

 

·         Create a HTML file (using JCreator) to contain at least the following code:

<APPLET CODE="HelloApplet.class" WIDTH=400 HEIGHT=400></APPLET>

 

·         Execute (do NOT compile) the HTML file using the execute button of JCreator.

 

Notes:

o        An applet must be declared as public and as extension of the standard class Applet

o        Although the paint() method receives a Graphics object, we should always cast it to Graphics2D which has better and more consistent methods for manipulating graphical shapes.

 

2.  Drawing simple graphical shapes

To draw a graphical shape, we first create the graphic object then call the draw() or fill() method of the Graphics2D to display it on the screen.

The following example draws various shapes on the screen.

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import java.awt.geom.Ellipse2D;

import java.awt.geom.Line2D;

 

public class Shapes extends Applet {

      public void paint(Graphics g) {

            Graphics2D g2 = (Graphics2D) g;          

            g2.drawString("Welcome to Bashir's Home Page", 10, 50);

           

            Line2D.Double line = new Line2D.Double(10,55, 300,55);     

            Rectangle rectangle = new Rectangle(10,70,300,200);        

            Ellipse2D.Double ellipse = new Ellipse2D.Double(20,80,280, 180);

           

            g2.draw(line);

            g2.draw(rectangle);

            g2.draw(ellipse);

            g2.drawString("Ahlan wa Sahlan", 50, 180);           

      }

}

 

3.  Changing Colors and Fonts

The Graphics2D object as seen in the above example draws and fills garphical shapes using the default color, which is black.

We can change the color by calling its setColor() method and passing to it any of the following colors pre-defined in the Color class.

Color

RGV Value

Color

RGV Value

Color.black

0.0F,  0.0F,  0.0F

Color.magenta

1.0F,  0.0F,  1.0F

Color.blue

0.0F,  0.0F,  1.0F

Color.orange

1.0F,  0.8F,  0.0F

Color.cyan

0.0F,  1.0F,  1.0F

Color.pink

1.0F,  0.7F,  0.7F

Color.gray

0.5F,  0.5F,  0.5F

Color.red

1.0F,  0.0F,  0.0F

Color.darkGray

0.25F,  0.25F,  0.25F

Color.white

1.0F,  1.0F,  1.0F

Color.lightGray

0.75F,  0.75F,  0.75F

Color.yellow

1.0F,  1.0F,  0.0F

Color.green

0.0F,  1.0F,  0.0F

 

 

 

We can also creat our own color object by specifying a a float value for each of the three primary colors (Red, Green and Blue)

Color myColor = new Color(0.2F, 0.7F, 0.55F);

 

Similarly, the default font can be changed by creating a Font object and passing it to the setFont() method of the Graphics2D object.    To create a Font object, we need to specify the font name, the style and the size.   The font name can be any font available on the computer or any of the following logical names:

Name

Description.

Serif

A font with small segments at the end, e.g. Times New Roman

SansSerif

A font without small segments. e.g. Helvetica or Arial

Monospaced

A font in which all characters have the same width. e.g. Courier

 

The font style can be any of : Font.PLAIN, Font.BOLD, Font.ITALIC, or Font.BOLD + Fond.ITALIC

 

The following example modifies the previous by changing colors and fonts.

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import java.awt.geom.Ellipse2D;

import java.awt.geom.Line2D;

import java.awt.Color;

import java.awt.Font;

 

public class FontAndColors extends Applet {

      public void paint(Graphics g) {

            Graphics2D g2 = (Graphics2D) g;

           

            Color myColor = new Color(0.2F, 0.7F, 0.5F);

            Font font1 = new Font("Serif", Font.BOLD, 22);

            Font font2 = new Font("SansSerif", Font.ITALIC, 30);

           

            setBackground(Color.cyan);         

            g2.setColor(Color.red);

            g2.setFont(font1);

            g2.drawString("Welcome to Bashir's Home Page", 10, 50);

           

            Line2D.Double line = new Line2D.Double(10, 55, 300, 55);

            Rectangle rectangle = new Rectangle(10,70,300,200);        

            Ellipse2D.Double ellipse = new Ellipse2D.Double(20,80,280, 180);

           

            g2.setColor(Color.red);

            g2.draw(line);

            g2.setColor(Color.blue);

            g2.fill(rectangle);          

            g2.setColor(Color.yellow);

            g2.fill(ellipse);      

            g2.setColor(myColor);

            g2.setFont(font2);

            g2.drawString("Ahlan wa Sahlan", 50, 180);           

      }

}

 

4.  Introducing the init() method

Recall that in addition to the paint() method, an an applet can also have the following methods: init(), start(), stop() and destroy().  When does the browser execute each of them?

 

Since the paint() method is executed each time something happens to the browser, and since we only need to create the various objects once, our applet in the above example will be more efficient if we create the objects in the init() method so that the paint() method only needs to draw or fill them.

 

However, there is a problem here.  If we declare the reference variables inside the init() method, then we cannot use them inside the paint() method.  Why?

 

To solve this problem, we declare the variables outside both methods, then create the objects inside init() method and finally draw or fill them inside the paint() method.  The following example illustrates this.

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import java.awt.geom.Ellipse2D;

import java.awt.geom.Line2D;

import java.awt.Color;

import java.awt.Font;

 

public class FontAndColors2 extends Applet {

 

      Font font1;

      Font font2;

      Color myColor;

      Line2D.Double line;

      Rectangle rectangle;

      Ellipse2D.Double ellipse;

     

      public void init() {

            myColor = new Color(0.2F, 0.7F, 0.5F);

            font1 = new Font("Serif", Font.BOLD, 22);

            font2 = new Font("SansSerif", Font.ITALIC, 30);

            line = new Line2D.Double(10, 55, 300, 55);           

            rectangle = new Rectangle(10,70,300,200);      

            ellipse = new Ellipse2D.Double(20,80,280, 180);

      }

           

      public void paint(Graphics g) {

            Graphics2D g2 = (Graphics2D) g;

           

            setBackground(Color.cyan);         

            g2.setColor(Color.red);

            g2.setFont(font1);

            g2.drawString("Welcome to Bashir's Home Page", 10, 50);    

            g2.setColor(Color.red);

            g2.draw(line);   

            g2.setColor(Color.blue);

            g2.fill(rectangle);

            g2.setColor(Color.yellow);

            g2.fill(ellipse);

            g2.setColor(myColor);

            g2.setFont(font2);

            g2.drawString("Ahlan wa Sahlan", 50, 180);           

      }

}

 

5.  Reading input into an applet

One way of reading input into an applet is by using the input dialog window.  To do this, we use the showInputDialog() method of the JOptionPane class, which is contained in the javax.swing package.  This method returns a string, thus if we need a number, we must use the appropriate parse method to convert.

 

The next example modifies the above by reading the user’s name instead of using Bashir.

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import java.awt.geom.Ellipse2D;

import java.awt.geom.Line2D;

import java.awt.Color;

import java.awt.Font;

import javax.swing.JOptionPane;

 

public class InputWindow extends Applet {

 

      Font font1;

      Font font2;

      Color myColor;

      Line2D.Double line;

      Rectangle rectangle;

      Ellipse2D.Double ellipse;

      String name;

     

      public void init() {

            name = JOptionPane.showInputDialog("Enter your name:");

            myColor = new Color(0.2F, 0.7F, 0.5F);

            font1 = new Font("Serif", Font.BOLD, 22);

            font2 = new Font("SansSerif", Font.ITALIC, 30);

            line = new Line2D.Double(10, 55, 300, 55);     

            rectangle = new Rectangle(10,70,300,200);

            ellipse = new Ellipse2D.Double(20,80,280, 180);

      }

           

      public void paint(Graphics g) {

            Graphics2D g2 = (Graphics2D) g;

           

            setBackground(Color.cyan);         

            g2.setColor(Color.red);

            g2.setFont(font1);

            g2.drawString("Welcome to "+name+"'s Home Page", 10, 50);

            g2.setColor(Color.red);

            g2.draw(line);   

            g2.setColor(Color.blue);

            g2.fill(rectangle);          

            g2.setColor(Color.yellow);

            g2.fill(ellipse);      

            g2.setColor(myColor);

            g2.setFont(font2);

            g2.drawString("Ahlan wa Sahlan", 50, 180);           

      }

}

 

Another way of reading input into an applet is to use the PARAM tag to specify the input in the HTML file.  The getParameter() method is then used in the applet program to read the input from the HTML file.  Again the getParameter method returns a string, thus if numbers are required, conversion must be done. 

 

The following HTML file is used to pass the name of the user and the values for creating the color object (myColor) used in printing the “Ahlan wa Sahlan” message.

 

<APPLET CODE="InputParameters.class" WIDTH=400 HEIGHT=400>

      <PARAM NAME = "Name"  VALUE = "Ibrahim">

      <PARAM NAME = "Red"  VALUE = "0.6">

      <PARAM NAME = "Green"  VALUE = "0.2">

      <PARAM NAME = "Blue"  VALUE = "0.4">

</APPLET>

 

To read the above parameters by the applet, the init() method is modified as follows:

The full modified program is in a file named InputParameters.java

 

      public void init() {

            float red, green, blue;

           

            name = getParameter("Name");

            red = Float.parseFloat(getParameter("Red"));

            green = Float.parseFloat(getParameter("Green"));

            blue = Float.parseFloat(getParameter("Blue"));

           

            myColor = new Color(red, green, blue);

            font1 = new Font("Serif", Font.BOLD, 22);

            font2 = new Font("SansSerif", Font.ITALIC, 30);

            line = new Line2D.Double(10, 55, 300, 55);

            rectangle = new Rectangle(10,70,300,200);

            ellipse = new Ellipse2D.Double(20,80,280, 180);

      }

 

6.  Displaying Images and Sound

Java allows images of type .gif or .jpg to loaded into an applet.  To do this, we create an object of class Image (of java.awt package) using the getImage() method.  The getImage() method need two arguments; the base URL and the relative URL.  The base URL is either the location of the applet class file, which can be obtained using the getCodeBase() method or the location of the HTML file, which can be obtained using the getDocumentBase() method.  The relative URL is the location of the image file (including the file name) relative to the base URL.  In our case, since the applet class file and the HTML file are stored in the same folder, we can use any of the methods (getCodeBase() or gerDocumentBase()) to get the base URL.

 

Java also allows sound files of type .au or .wav to be loaded and played in an applet.  To do this, we create an object of class AudioClip (of the java.applet package) using the getAudioClip() method.  The getAudioClip() method also need base URL and relative URL as explained above.  One the AudioClip object is created, we can use its methods play(), loop() and stop() to play the audio.

 

The following example loads an image and displays it on two places in the applet window.  It also loads and plays an audio continuosly.

 

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Image;

import java.applet.AudioClip;

 

public class ImagesAndSound extends Applet {

 

      Image olympic;

      AudioClip music;

 

      public void init() {

            olympic = getImage(getCodeBase(), "images/olympiclogo.gif");

            music = getAudioClip(getDocumentBase(), "audio/spacemusic.au");

      }

     

      public void paint(Graphics g) {

            int width = olympic.getWidth(this);

            int height = olympic.getHeight(this);

           

            g.drawImage(olympic, 100, 10, this);

            g.drawImage(olympic, 40, height+15 , width*2, height*2, this);

            music.loop();

      }

}

 

 


7.  Assignment.

1.        Write an applet that will display the following on a white background.  Use the following dimension:

Rectangle:       (10, 10, 300, 150), fill color: blue

Left circle:      (10, 10, 150, 150), fill color: yellow

Right circle:    (159, 10, 150, 150), fill color: yellow

Text:              (110, 90), color:  red

 

 

2.        (a)  Write an applet that uses Input Dialog Window to reads the users name and age and then prints output as follows:

Hint:  You need to create two font objects as follows:

First font:  Serif,  BOLD, size = 28

Second font: SansSerif, ITALIC, size = 28

   You also need to call drawString() method four times at (10, 50),  (10, 100),  (100, 50)  and (210, 100).

 

 

(b)  Modify the applet in (a) above so that the input is read from the HTML file.

 

3.        Write an applet that will display three Saudi flags in a white background in the following form.  Your applet must also play adhan.wav continuously.  The adhan file is in the audio sub-folder and the flag is in the images sub-folder: