Download In Java, it is possible for a class to inherit the characteristics of

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM
ICS102, SECTIONS 57, 58 (001 Semester)
INTRODUCTION TO COMPUTING
LABWORK #03: Introduction to HTML and Applets
Objectives:
To gain experience with:




writing simple applets
writing basic HTLM codes to execute applets
displaying graphics such as rectangles, ellipses and lines
using colors and fonts
HTML (Hypertext Markup Language): A language used to define Web pages.
Web browser: A Web browser is a software that retrieves HTML documents across network connections and formats
them for viewing. A browser is the primary vehicle for accessing the World-wide web.
Java application: A Java program that can be run without the use of a Web browser.
Applet: A Java program that is linked into an HTML document. It is retrieved and executed using a web browser.
Applets do not usually have main( ) method; instead they have a function called init( ) which, like main( ) is invoked by
the execution environment.
A Java applet must be compiled into bytecode before it can be used in a Web page. It is this bytecode that is linked to an
HTML document and sent across the Web. A version of the Java interpreter embedded in the Web browser is then used
to execute the applet once it reaches its destination.
Applets are placed on a web page using the <APPLET> tag. The purpose of <APPLET> is to place an applet on a Web
page and control how it looks in relation to other parts of the page.
Example:
<APPLET CODE= “AppletName.class” WIDTH=600 HEIGHT=100>
</APPLET>
In this example, the <APPLET> tag includes three attributes:
 CODE
Specifies the name of the applet’s main class file
 WIDTH
Specifies the width of the applet window on the Web page.
 HEIGHT
Specifies the height of the applet window
The class file indicated by the CODE attribute must be in the same folder as the Web page containing the applet,
unless you use a CODEBASE attribute to specify a different folder.
It is customary (but not necessary) to give the HTML file the same name as that of the applet class inside.
Appletviewer: An appletviewer is a utility used to display an applet as it would be seen in the browser; but without
displaying any of the HTML document itself.
There are two ways in which you can run an applet:
1. Executing the applet within a Java-compatible Web browser, such as Internet explorer or netscape
2. Using an applet viewer, such as the standard JDK tool appletviewer.
2
INHERITANCE
In Java, it is possible for a class to inherit the characteristics of another class. A class that is inherited is called a
superclass. The class that does the inheriting is called a subclass. A subclass inherits all instance variables and methods
defined in the superclass and adds its own variables and/or methods.
superclass
subclass
A superclass and its subclass define an “is-a” relationship. A subclass is a superclass (with some additional
characteristics). For example, the class Student is a subclass of the class Person. A student is a person.
In Java, the keyword extends is used to denote inheritance. The general form of a subclass inheriting another class is:
class subclassName extends superclassName
{
. . .
}
All applets are subclasses of the Applet class contained in the java.applet package.
Applets interact with the user through the Abstract Window toolkit (AWT) classes. The AWT contains support for a
window-based, graphical interface.
Thus the general form of an Applet is:
import java.awt.*;
import java.applet.*;
public class AppletName extends Applet
{
. . .
}
Note:
1. The class Applet name must be declared public; because it will be accessed by code that is outside the program
(i.e., the browser or applet viewer).
2. The class Applet has a subclass called JApplet that is contained in the javax.swing package. JApplet has more
functionality than Applet. Applets that are subclasse of JApplet have the general form:
import java.awt.*;
import javax.swing.*;
class AppletNamePanel extends JPanel
{
. . .
}
public class AppletName extends JApplet
{
. . .
}
We will not study JApplets in ICS 102.
3
A portion of the java.awt class hierarchy, relevant to our discussion on Applets, is given below. Note that all the classes
shown in the hierarchy are in the java.awt package except Object and JApplet. Object, a class inherited by all other
classes, is in the java.lang package. JApplet is in the javax.swing package.
Object
Color
Font
FontMetrics
Component
Container
Graphics
Graphics2D
Panel
Applet
JApplet
Class Color contains methods and constants for manipulating colors. Class Font contains methods and constants for
manipulating fonts. Class FontMetrics contains methods for obtaining font information. Class Graphics contains
methods for drawing strings, lines, rectangles, ellipses, and other shapes. Class Graphics2D adds extensive new
functionality to the Graphics class.
OVERRIDING METHODS
A method is a superclass is overridden in a subclass if the subclass has a method with the same name, return type, and
parameter list as the method. A call to the overridden method from within the subclass will always refer to the version
of that method defined by the subclass. The method defined by the superclass will be hidden to the subclass.
Example:
class Display1
{
int x = 50 ;
int y = 30 ;
void printMe( )
{
System.out.println(“ x = ” + x + “ , y = ” + y);
}
}
public class Display2 extends Display1
{
int z = 3 ;
4
void printMe( )
{
System.out.println(“ x = ” + x + “ , z = ” + z);
}
public static void main(String[ ] args)
{
Display2 myObject = new Display2( );
MyObject.printMe( ) ;
}
}
The output of the above program is:
x = 50 , z = 3
indicating that it is the printMe( ) method of Displa2 that is invoked. This is because when an object’s method is called,
Java starts to look for that method’s definition in the object’s class. Only if it does not find the definition does it pass the
method call up the class hierarchy until the method definition is found.
AN APPLET SKELETON
All but the most trivial applets override a set of methods that provide the basic mechanism by which the browser or
applet viewer interfaces to the applet and controls its execution. Four of these methods – init( ), start( ), stop( ), and
destroy( ) are defined in the class Applet. Another method , paint( ), is defined in the AWT Component class. Default
implementations for all these methods are provided. APPLETS DO NOT NEED TO OVERRIDE THOSE METHODS
THEY DO NOT USE. In the simple applets we will write, we will override paint( ) and sometimes the init( ) method.
The general structure of an applet is:
import java.awt.*;
import java.applet.*;
public class AppletName extends Applet
{
public void init( )
{
. . .
}
public void start( )
{
. . .
}
public void stop( )
{
. . .
}
public void destroy( )
{
. . .
}
public void paint(Graphics g )
{
. . .
}
}
5
Applet initialization and termination
When an applet begins, the AWT calls the following methods, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of methods takes place:
1. stop( )
2. destroy( )
init( )
This method is called by the execution environment (i.e., the applet viewer or browser) when an applet begins
execution. It is the first method called for any applet. This method is called only once during the run time of your applet.
This is where you should initialize variables and set the background and foreground colors of the applet.
start( )
This method is called by the execution environment (i.e., the applet viewer or browser) when an applet should start or
resume execution. It is automatically called after init( ) when an applet first begins.
stop( )
This method is called by the execution environment (i.e., the applet viewer or browser) to suspend execution of the
applet. Once stopped, an applet is restarted when the execution environment calls start( ).
destroy( )
This method is called by the execution environment (i.e., the applet viewer or browser) just before the applet is
terminated. Your applet should override this method if it needs to perform any cleanup prior to its destruction.
paint( )
The paint method is called by the execution environment (i.e., the applet viewer or browser) each time your applet’s
output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is
running may be covered by another window and then uncovered. Or the applet window may be minimized and then
restored. paint( ) is also called when the applet begins execution.
The paint method that is inherited from the class Applet is an empty method. In order for anything to be displayed on
the applet window, the paint( ) method must be overridden, in your Applet subclass, with behavior to display text,
graphics, and other things.
The paint method takes an object of class Graphics as an argument. The Graphics object is passed to the paint method
by the execution environment (i.e., the applet viewer or browser). It is the AWT that takes care of creating the Graphics
object passed to paint. An object of class Graphics represents a particular drawing surface and it contains methods for
drawing, font manipulation, color manipulation, etc.
Since an object of class Graphics is passed to paint( ), to use the functionality provided by the Graphics2D class, the
object must be converted to a Graphics2D object. This is done by a type cast:
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g ;
. . .
}
Colors
The class Color defines several static variables that hold references to various Color objects. These variables are: black,
blue, cyan, dark gray, gray, green, lightGray, magenta, orange, pink, red, white, and yellow. Because the variables are
static, they can be referenced using the class name, example: Color.red
All colors can be specified as a mix of three primary colors: red, green, and blue. Java uses the RGB color model, where
colors are specified by giving the amount of the primary colors that make up the color. A particular color can be
specified by either three integers, each between 0 and 255, or by three float values, each between 0.0 and 1.0. The
integer values specify the color as a mix of red, green, and blue. The float values specify the relative mix of red, green,
and blue.
6
Color
Color.black
Color.blue
Color.cyan
Color.gray
Color.darkGray
Color.lightGray
Color.green
Color.magenta
Color.orange
Color.pink
Color.red
Color.white
Color.yellow
RGB Value (Float)
0.0F, 0.0F, 0.0F
0.0F, 0.0F, 1.0F
0.0F, 1.0F, 1.0F
0.5F, 0.5F, 0.5F
0.25F, 0.25F, 0.25F
0.75F, 0.75F, 0.75F
0.0F, 1.0F, 0.0F
1.0F, 0.0F, 1.0F
1.0F, 0.8F, 0.0F
1.0F, 0.7F, 0.7F
1.0F, 0.0F, 0.0F
1.0F, 1.0F, 1.0F
1.0F, 1.0F, 0.0F
RGB Value (Integer)
0, 0, 0
0, 0, 255
0, 255, 255
128, 128, 128
64, 64, 64
192, 192, 192
0, 255, 0
255, 0, 255
255, 200, 0
255, 175, 175
255, 0, 0
255, 255, 255
255, 255, 0
Because the value of each primary color contribution can range from 0 to 255, we can define over 16 million different
colors (2553). The differences between some of these colors are so subtle that it is difficult to distinguish between them.
You can create your own color objects, using one of the following Color constructors:
Color(int red, int green, int blue)
Color(float red, float green, float blue)
Example:
import java.awt.Color;
. . .
Color c1 = new Color(255, 100, 18);
Color c2 = new Color(0.2F, 0.6F, 0.3F);
. . .
By default, displays on the applet window are in black on a light gray background. This default can be changed by using
the methods: setBackground( ), setForeground( ), setColor( ). These methods set the background color of the display
surface, the foreground color of the display surface, and the foreground color of the displayed object respectively. Note
that the foreground color of the display surface will be the display color of any object drawn on the display surface, if
there is no call to setColor( ). The general forms of these methods are:
void
void
void
setBackground(Color newColor)
setForeground(Color newColor)
setColor(Color newColor)
Although it is possible to set the background and foreground colors in the paint( ) method, a good place to set
these colors is in the init( ) method.
Example: The following Applet outline shows how to set colors.
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
public void init( )
{
setBackground(Color.blue) ;
setForeground(Color.yellow) ;
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g ;
// Objects displayed here will use the foreground color yellow
7
g2.setColor(Color.red) ;
// Objects displayed here will use the color red
g2.setColor(Color.magenta) ;
// Objects displayed here will use the color magenta
Color c1 = new Color(255, 100, 18);
g2.setColor(c1) ;
// Objects displayed here will use the color c1
}
}
Note: It is possible to set the color c1 in the above example without explicitly creating the color object c1:
g2.setColor(new Color(255, 100, 18) ) ;
It is possible to obtain the current settings for the background and foreground colors by calling getBackground( ) and
getForeground( ), respectively:
Color getBackground( )
Color getForeground( )
A Graphics object coordinate system
A graphics object, such as the parameter g for the paint( ) method can be thought of as an area of the screen. Within this
area of the screen, you use x- and y-coordinates to refer to a particular spot. A graphics object has a coordinate system
that is illustrated below:
(0, 0)
x
y
The origin point (0, 0) is the upper left-hand corner of the graphics object. The x-coordinate is positive and increasing to
the right. The y-coordinate is positive and increasing in a downward direction.
Displaying messages in the applet window
To output a string to an applet, use the drawString( ) method. It has the following general form:
void drawString(String message , int x , int y)
where message is the string to be output beginning at the point (x , y)
Note: The drawString( ) method does not recognize the new line character ‘\n’.
8
Example : The following applet displays the message: Hello Word in black on a light gray background.
import java.applet.*;
import java.awt.*;
public class HelloApplet extends Applet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g2 ;
g2.drawString("Hello world!", 50, 25);
}
}
Example: The following applet displays strings in various colors on a blue background:
import
import
java.awt.*;
java.applet.*;
public
{
class
public
{
MyApplet
void
extends
Applet
init( )
setBackground(Color.blue) ;
setForeground(Color.yellow) ;
}
public
{
void
paint(Graphics
Graphics2D
g2
=
g)
(Graphics2D)
g ;
g2.drawString("A yellow string", 50, 10);
g2.setColor(Color.red) ;
g2.drawString("A red string", 50, 50);
g2.drawString("Another red string", 50, 90);
g2.setColor(Color.magenta) ;
g2.drawString("A magenta string", 50, 130);
g2.setColor( getForeground( ) ) ;
g2.drawString("Another yellow string", 50, 170);
}
}
Displaying messages in the status window
In addition to displaying information in its window, an applet can also output a message to the status window of the
browser or applet viewer on which it is running. To do so, call showStatus( ) with the string you want displayed. The
status window is a good place to give the user feedback about what is occurring in the applet, or possibly report some
types of errors.
Example:
import
import
java.awt.*;
java.applet.*;
public
class
StatusWindow
extends
Applet
9
{
public void init( )
{
setBackground(Color.cyan) ;
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)
g ;
g2.drawString("This is in the applet window", 10, 20);
showStatus(“This is shown in the status window.”);
}
}
Displaying messages in the console window
If an applet has a System.out.println( ) or System.out.print( ), then the output for that statement is not in the applet
window but rather to the console window.
Example:
import
import
java.awt.*;
java.applet.*;
public
{
class
ConsoleWindow
extends
Applet
public void init( )
{
setBackground(Color.cyan) ;
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)
g ;
g2.drawString("This is in the applet window", 10, 20);
System.out.prinln(“This is shown in the console window.”);
}
}
Fonts and Font metrics
By default, strings are drawn using the default font, plain style and default font size.
To change the font, style or size, we need to create an object of class Font and pass it to the setFont method of the
Graphics2D object. To create such object, we need to specify the following parameters:

The font name

The Style (Font.PLAIN, Font.BOLD, Font.ITALIC, or Font.BOLD + Fond.ITALIC)

The point Size
The font name can be the name of any font available on the particular computer (such as: TimesRoman, Courier,
Helvetica etc.,) or any of the logical names shown in the table below:
Name
Serif
SansSerif
Monospaced
Dialog
DialogIput
Description.
A font with small segments at the end, e.g. Times New Roman
A font without small segments. e.g. Helvetica
A font in which all characters have the same width. e.g. Courier
A screen font suitable for labels in dialogs
A screen font suitable for user input in text field
Note: Using the logical name is recommended since it makes the applet more portable.
10
Example: The following prints the word Applet in large SansSerif font.
import
import
import
import
import
java.applet.Applet;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.Font;
java.awt.Color;
public class BigFontApplet extends Applet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
final int SIZE = 48;
Color myColor = new Color(0.25F, 0.5F, 0.75F);
Font myFont = new Font("SansSerif", Font.BOLD, SIZE);
g2.setColor(myColor);
g2.setFont(myFont);
g2.drawString("Applet",5,60);
}
}
Note: Although it is possible to create Font objects in the paint( ) method, as in the above example, a good place
to do so is in the init( ) method.
Example:
import
import
import
import
import
java.applet.Applet;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.Font;
java.awt.Color;
public class FontsApplet extends Applet
{
private Font font1, font2, font3;
public void init( )
{
setBackground(Color.yellow);
font1 = new Font("TimesRoman", Font.BOLD, 12);
font2 = new Font("Courier", Font.BOLD + Font.ITALIC, 24);
font3 = new Font("Helvetica", Font.PLAIN, 14);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.blue);
g2.setFont(font1);
g2.drawString("I like ICS 102 very much", 20, 20);
g2.setColor(Color.red);
g2.setFont(font2);
g2.drawString("I also like to do the homework", 20, 40);
g2.setColor(Color.black);
g2.setFont(font3);
g2.drawString("I also like applets !", 20, 60);
11
}
}
Note: The instance variables font1, font2, and font3 are declared as private. This means they cannot be accessed
outside their class.
Drawing lines.
To draw a line, we need to create an object of class Line2D.Double of the java.awt.geom. package. To create such
object, we need to specify the two end-points the line. This can be done in two ways:
By giving the x and y coordinates of both points as in:
Line2D.Double line1 = new Line2D(x1, y1, x2, y2);
Or we can specify each point as an object as in,
Point2D.Double from = new Point2D.Double(x1, y1);
Point2D.Double to = new Point2D.Double(x2, y2);
Line2D.Double line1 = new Line2D.Double(from, to);
The latter method is more object-oriented and more useful particularly if the point objects need to be re-used.
Example : The following applet draws a Triangle.
import
import
import
import
import
import
java.applet.Applet;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.geom.Ellipse2D;
java.awt.geom.Line2D;
java.awt.geom.Point2D;
public class TriangleApplet extends Applet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Point2D.Double pointA = new Point2D.Double(30,10);
Point2D.Double pointB = new Point2D.Double(10,50);
Point2D.Double pointC = new Point2D.Double(50,50);
Line2D.Double lineAB = new Line2D.Double(pointA, pointB);
Line2D.Double lineBC = new Line2D.Double(pointB, pointC);
Line2D.Double lineCA = new Line2D.Double(pointC, pointA);
g2.draw(lineAB);
g2.draw(lineBC);
g2.draw(lineCA);
}
}
Drawing a rectangles
To draw a rectangle, we need to crate an object of class Rectangle2D and then draw it using the draw method of the
Graphics2D object. To create an object of class Rectangle, we need to specify the following parameters:

The top-left corner of the rectangle (x, y co-ordinates)

The width of the rectangle

The height of the rectangle.
Example : The following applet draws a rectangle
import
import
import
import
public
{
java.applet.Applet;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.Rectangle;
class RectangleApplet extends Applet
12
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Rectangle2D.Double rectangle = new Rectangle2D.Double(10,10,50,50);
g2.draw(rectangle);
}
}
Note: If we replace the g2.draw(rectangle); with g2.fill(rectangle); in the above example, we get
a solid rectangle.
Drawing Ellipses.
To draw an Ellipse, we need to import the Ellipse2D class of the java.awt.geom. package. However, the Ellipse2D class
contained two Ellipse classes, Ellipse2D.Float which uses floating point coordinates and Ellipse2D.Double which stores
its co-ordinates in double. Since double is the default for floating point representation in Java, we shall be using
Ellipse2D.Double.
Similarly to draw a circle, we need to create an object of class Ellipse2D.Double and then use the draw method of the
Graphics2D object to draw it. To create such object, we need to specify the parameters for the rectangle bounding the
circle.
Example : The following example draws two concentric circles.
import
import
import
import
java.applet.Applet;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.geom.Ellipse2D;
public class CircleApplet extends Applet
{
public void paint(Graphics g)
{ Graphics2D g2 = (Graphics2D)g;
Ellipse2D.Double circle1 = new Ellipse2D.Double(10,10,50,50);
Ellipse2D.Double circle2 = new Ellipse2D.Double(20,20,30,30);
g2.draw(circle1);
g2.draw(circle2);
}
}