applets and graphics yangjun chen dept. business computing university of winnipeg

48
Jan. 2004 1 Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Upload: gemma-ware

Post on 02-Jan-2016

21 views

Category:

Documents


0 download

DESCRIPTION

Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg. Outline: Applets and Graphics. Applet -HelloWorld Applet -import statement -Hypertext Mark Language (HTML) Graphic -line, rectangle, polygon, ovals, arcs, color, font. Applets. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 1

Applets and Graphics

Yangjun Chen

Dept. Business ComputingUniversity of Winnipeg

Page 2: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 2

Outline: Applets and Graphics

• Applet- HelloWorld Applet

- import statement- Hypertext Mark Language (HTML)

• Graphic- line, rectangle, polygon, ovals, arcs, color, font

Page 3: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 3

Applets

• There are two types of Java programs:- Applications and Applets

• We will focus on applets today.- an applet is a Java program that can be viewed on a Web browser that supports the Java language.

• The easiest way to explain what an applet is and how itworks is by example.

• Let’s look at the applet-version of the HelloWorld example from the first class in greater detail.

Page 4: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 4

HelloWorld Applet

• The HelloWorld applet:

import java. applet.*;import java. awt.*;// A simple Java Appletpublic class HelloWorld extends Applet

{public void paint( Graphics g)

{g. drawString(“ HelloWorld!”, 20,10);

}}

Page 5: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 5

HelloWorld Applet

• After compiling the code, the class file is called by an HTML document in a web browser or applet runner (appletviewer) and the output will be displayed on the screen.

• The HTML code (stored in file HelloWorld.html) to call an applet is:

<applet code = “filename.class”width = “width of applet in pixels”height = “height of applet in pixels”>

</applet>• applet runner:

- appletviewer HelloWorld.html

Page 6: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 6

HelloWorld Applet• Example (HelloWorld.html):

<HTML><BODY><APPLET CODE = HelloWorld.class

WIDTH = 200 HEIGHT=200>

</ APPLET></BODY></HTML>

URL address: file://e:/javaprog/HelloWorld.html

Page 7: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 7

Life Cycle of an Applet• An Applet executes within an environment

provided by a Web browser or a tool such as the applet viewer.

• It does not have a main() method• There are four methods that are called during the

life cycle of an applet:init(),start(),stop(),destroy().

Page 8: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 8

Life Cycle of an Applet• init() method is called only when the applet begins execution.

It is common to place code here that needs to be executed only once, such as reading parameters that are defined in the HTML file.

• start() method is executed after the init() method completes execution. In addition, this method is called by the applet viewer or Web browser to resume execution of the applet.

• stop() method is called by the applet viewer or Web browser to suspend execution of an applet.- the start() and stop() methods may be called multiple times during the life cycle of the applet.

Page 9: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 9

Life Cycle of an Applet• destroy() method is called by the aplet viewer or Web

browser before the applet is terminated.

import java.applet.*;import java.awt.*;//A simple java Applet

public class AppletLifecycle extends Applet {String str = "";

public void init() {str += "init; ";}

Page 10: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 10

public void start() {str += "start; ";

}public void stop() {

str += "stop; ";}

public void destroy() {System.out.println(str + "destroy; ”);

}public void paint(Graphics g) {

g.drawString(str, 10, 25);}}

Life Cycle of an Applet

Page 11: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 11

import Statements

• The first two lines of the program are:

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

• These two lines “import” or let the Java compiler

knowthat we want to use classes that are in the

packagesjava. applet and java. awt.

- The java. applet package:contains definitions for the applet class

- The java. awt package:contains classes for displaying graphics

Page 12: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 12

import Statements

• The “*” acts as a wildcard that will import all of theclasses in the package

• Difference between this “*” and the one used at a commandprompt.- You can not use it to indicate partial names such as L* to

import all the classes that start with L.• The “*” will import all the public classes in a

package butdoes not import the subpackages.

Page 13: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 13

import Statements

- To import all classes in a package hierarchy, you must import each level (or subpackage) explicitly.

import java. awt.*; does not import the “peer” subpackage.

To import the “peer” subpackage you must do it explicitly.

Example:import java. awt.event.*;import.java.awt.image.*;

Page 14: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 14

import Statement Syntax

• The form of an import statement is as follows:- import packageName .*;

orimport packageName. className ;Examples: import java.applet.Applet;

import java.awt.Graphics;• import statements must appear before any of the names

defined in the import are used.• It is a strong recommendation that all imports

appear at thebeginning of your program.

Page 15: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 15

Importing Classes

• Should you take time to import classes individually orimport them as a group?- Importing them as a group does not add any overhead

because only the classes that are used in your code areactually loaded as they are needed.

- Importing classes as a group makes it a little more confusing

for others reading your code to figure out where your classes

are coming from.- The textbook prefers the first method.- It is really up to your own coding style.

Page 16: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 16

drawString() method

• The drawString() method belongs to the Graphics class

• g is a Graphics object and we want it to execute it’s owndrawString() method.

• We also pass it what we want to draw on the screen andwhere we want the graph to be drawn.

• The drawString() method is defined in the Graphics asfollows:

Public void drawString( String s, int x, int y){

Code to draw s on the screen at location x, y}

Page 17: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 17

Where does paint() start?

• We are finished with the program, but where does thepaint() method invoked?

• A lot of actions in a Java program are done behind the scenesand in this case it is up to the Web browser or

applet runner to decide when to invoke the paint() method.• It could be when the applet first appears, when

you resize awindow, or when you uncover the applet.

Page 18: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 18

Hypertext Markup Language (HTML)

• HTML is a purely text based language.• All Web browsers are designed to recognize

HTML.• HTML elements are known as tags which consist

ofkeywords that are enclosed between angle

brackets, “<“and “>”: <H1>

• Everything that is not a tag is considered to be plain textand displayed by your browser.

• HTML is platform independent.

Page 19: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 19

HTML Tags

• HTML tags are case- insensitive, but are usually capitalizedto make them stand out.

• A tag is enclosed in angle brackets, for example <H1> is atag that would make a level 1 heading. To end

the level 1heading we would put in an end tag </H1>.- Example:

<H1> This is a level one heading </H1>This would appear on the screen as:

This is a level one heading<H6> This is a level six heading </H6>

This is a level one heading

Page 20: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 20

HTML Tags

• HTML elements can not overlap:- the following is not allowed

<H1>< B> Bold and H1 overlap - this is illegal</ H1></ B>• Some elements can also take attributes:

- <H1 ALIGN=“ center”> This is a heading</ H1>

This will center the heading whenever it is possible.Attributes always appear in the the start tag of an

element.The value assigned to the attribute may be case

sensitive.<IMG SRC=“ filename. gif”>

in this case the filename is case- sensitive and is preserved

by putting the filename in quotation marks.

Page 21: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 21

HTML Skeleton

<HTML><!- Comment Line. -><HEAD><TITLE> This is the document Title</ TITLE></ HEAD><BODY>…This is the document text.…</ BODY></ HTML>

Page 22: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 22

Applet Tag

<HTML><!- Comment Line. -><HEAD><TITLE> This is the document Title</ TITLE></ HEAD><BODY>…<APPLET CODE=“ HelloWorld. class” width= 100height= 100></ APPLET>…</ BODY></ HTML>

Page 23: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 23

Some Common HTML Tags

• <BR> - This gives you an end of line• <HR> - Horizontal Rule - draws a horizontal line• <PRE>…</PRE> - Preformatted text - everything

betweenthe tags will appear on the web page as it does in

youreditor.

• <A HREF=“ someURL”> click here</A> - Creates ahyperlink to “someURL”

• <A HREF=“ mailto: name@ company. com”> text tohighlight</A> - sends an email to the address

given.• <IMG SRC=“ filename. gif”> - displays an image• <B> BOLD </B> <I> ITALICS </I>

Page 24: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 24

Building Your Web Page

• Your unix account should have a directory call“public_ html”- in this directory you should find a file called “index. html”- this is the file that the web browser will display by default

ifno specific file is specified in the URL.

“http:// www. uwinnipeg. ca” is the same as“http:// www. uwinnipeg. ca/public_html/index. html”

- You want to save your HTML with the filename “index. html”

Page 25: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 25

Graphics

• The java. awt package contains all the necessary classesyou need to create graphical user interfaces

(GUIs).• Most of the graphics operations in Java are

methodsdefined in the Graphics class.

• You don’t have to create an instance of the Graphics classbecause in the applet’s paint() method, a Graphics

object isprovided for you. By drawing in that object, you

drawonto your applet which appears on the screen.

• The Graphics class is part of the java. awt package, somake sure you import it into your Java code.- import java. awt. Graphics;

Page 26: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 26

The Coordinate System

• Java’s coordinate system has the origin (0,0) in the top leftcorner of the applet.- Positive x values are to the right and positive y values are

downward• The coordinate system is represented by pixels.

- Pixels in Java are integer values only(0,0)

(60,50)

+X

+Y

(20,20)

Page 27: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 27

Lines

• To draw a line onto the screen, use the drawLine() method:- void drawLine( int x1, int y1, int x2, int y2);- This draws a line from the point with coordinates (x1, y1)

to thepoint with coordinates (x2, y2).

- Example:import java. awt. Graphics;public class MyLine extends java. applet. Applet {

public void paint( Graphics g) {g. drawLine( 25,25, 75,75);

}}

- There is no way to change the line thickness in Java.So how do we make thicker lines?

Page 28: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 28

Rectangles

• To draw a rectangle on the screen, use the drawRect()method:- void drawRect( int x, int y, int width, int height)- This draws an outline of a rectangle with the top left

corner of therectangle having the point (x, y). The size of the rectangle

isgoverned by the width and height arguments.

• To fill in the rectangle we would use the method fillRect().This works in the same way as drawRect() but fills

in therectangle with the current drawing color.

• To change the current drawing color we use the method:- void setColor( Color c)- The drawing color stays fixed until it is changed by

another call tothe setColor() method.

Page 29: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 29

Rectangles

• Example:

import java. awt. *;public class MyRect extends java. applet. Applet {

public void paint( Graphics g) {g. drawRect(20,20, 60,60);g. setColor( Color. red);g. fillRect( 120, 20,60, 60);

}}

Page 30: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 30

Rounded Rectangles• These are rectangles with the corners rounded

according tothe values of the arguments.

• Like the rectangle, there are two methods for roundrectangles:- void drawRoundRect( int x, int y, int width, int height, int

arcWidth, int arcHeight)- void fillRoundRect( int x, int y, int width, int height, int arcWidth,

int arcHeight)

Page 31: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 31

3D Rectangles

• You can also draw three dimensional rectangles in Java- Warning: They really don’t look too good though

• There are two methods as well:- void draw3DRect( int x, int y, int width, int height, boolean raised)- void fill3DRect( int x, int y, int width, int height, boolean raised)- The argument “raised”, when true, will paint the rectangle as if it

were raised from the surface.- If it is false, the rectangle will appear as if it were

depressed.

Page 32: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 32

Polygons

• Polygons are shapes with an unlimited # of sides.• To draw a polygon, you need a set of x and y

coordinates.• The polygon is then drawn by drawing a series of

straightlines from the first point to the second, to the

third and soon.

• Once again, there is a drawPolygon() method and afillPoylgon() method.

• There are two ways to indicate the list of coordinates:- as arrays of x and y coordinates- as an instance of the Polygon class

• Note: Java will automatically close the polygon for you.- If you want to leave it unclosed, use the drawPolyline()

method.

Page 33: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 33

Polygon Using Arrays

• Example:

import java. awt. Graphics;public class MyPolygon extends java. applet. Applet {

public void paint( Graphics g) {int exes[]={ 39, 94,97, 142,53, 58,26};int whys[]={ 33,74, 36,70,108,80,106};int pts= exes. length;g. drawPolygon( exes, whys, pts);

}}

Page 34: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 34

Polygons using the Polygon Class

• The second way is to use a polygon object to store theindividual points of the polygon.- To create a new Polygon object:

Polygon poly= new Polygon();- or create a polygon from a set of points:

int exes[]={ 39, 94,97, 142,53, 58,26};int whys[]={ 33,74, 36,70,108,80,106};int pts= exes. length;Polygon poly= new Polygon(exes, whys, pts);

- with a Polygon object you can add points to the polygon as

needed:poly. addPoint( 20,35);

• So we can draw a polygon by passing our Polygon objectinto the drawPolygon() or fillPolygon() method.

Page 35: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 35

Polygons using the Polygon Class

• Example:

import java. awt. Graphics;import java. awt. Polygon;public class MyPolygon2 extends java. applet. Applet {

public void paint( Graphics g) {int exes[]={ 39, 94,97, 142,53, 58,26};int whys[]={ 33,74, 36,70,108,80,106};int pts= exes. length;Polygon poly= new Polygon( exes, whys, pts);g.drawPolygon(poly);g.fillPolygon( poly);

}}

Page 36: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 36

Ovals

• Ovals are drawn with the drawOval() or fillOval() methods- void drawOval( int x, int y, int width, int height)- void fillOval( int x, int y, int width, int height)- This draws an oval within the bounding rectangle

specified by thearguments

- Example:import java. awt. Graphics;public class MyOval extends java. applet. Applet {

public void paint( Graphics g) {g. drawOval( 20, 20, 60,60);g. fillOval( 120, 20,60,60);

}}

Page 37: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 37

Arcs• An arc is basically part of an oval.• Arcs are drawn using the method:—

- void drawArc( int x, int y, int width, int height, int startAngle, int arcAngle)

- void fillArc( int x, int y, int width, int height, int startAngle, intarcAngle)

- This draws an arc within the rectangle specified starting from the

startAngle argument for a duration of arcAngle.- Example:

g. drawArc( 10,10,100,80,45,210);

Page 38: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 38

Arcs

• Example:

import java. awt. Graphics;public class MyArc extends java. applet. Applet {

public void paint( Graphics g) {g. drawArc( 120,20, 60,60,90, 180);g. fillArc( 120,20,60, 60,90,180);

}}

Page 39: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 39

Graphics Exampleimport java.awt.*;public class Lamp extends java. applet. Applet{public void paint( Graphics g) {

g.setColor(Color.red);g. fillRect( 0,250, 290, 290); // lamp platformg. drawLine( 125, 250,125,160); // base of lampg. drawLine( 175, 250,175,160);g. drawArc( 85,157,130, 50,- 65,312); // lamp shadeg. drawArc( 85,87, 130,50, 62,58); // top & bottom edgesg. drawLine( 85,177,119, 89); // lamp shade sidesg. drawLine( 215, 177,181,89);g. fillArc( 78, 120,40, 40,63,- 174); // dots on shadeg. fillOval( 120, 90,40,40);g. fillArc( 173,100, 40,40,110,180);}

}

Page 40: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 40

Copying areas of the Screen

• After drawing things on the screen, you might want tomove things around

• The copyArea() method copies a rectangular area of thescreen to another area of the screen- void copyArea( int x, int y, int width, int height, int dx, int dy)- The first four arguments specify the rectangle to copy

and dx anddy represent the distance in the x and y direction.

- Exampleg. copyArea( 0,0,100,100,100,0);

Page 41: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 41

Clearing the screen

• Now that we have drawn things on the screen, we want toclear them.

• The way Java clears the screen is by drawing over it withthe background color.

• This method is called clearRect()- void clearRect( int x, int y, int width, int height)- This clears a rectangular area specified by the

arguments.

Page 42: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 42

The Color Class• This class contains 13 constant values that can be

used:- black, blue, cyan, darkGray, Gray, green, lightGray, magenta,

orange, pink, red, white, yellow• To address them we have to reference them

through theColor class- eg. Color. black- Too set the current color to blue:

g. setColor(Color. blue)• Colors in Java are described by the RGB (Red,

Green,Blue) model.- This model specifies the amount of red, green, and blue

in a color.- The intensity of each component is measured as an

integer between0 and 255, with 0 representing no light.

(0,0,0) is black(128,128,128) is medium gray

Page 43: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 43

The Color Class

• To declare a new color in Java, use the “new” operator- Color myColor = new Color( 255, 0, 128);- We now have a new color and since we know it is an

object of the Color class we can use it directlyg. setColor(myColor);

- You can also define the color “on the fly” or in line with the

setColor() methodg. setColor( new Color( 255,0,128));

Page 44: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 44

The Font Class• There are five basic fonts in Java

- SanSerif (Helvetica), Serif (Times Roman), Monospaced (Courier),Dialog, DialogInput

• There are some constant values associated with the Font classas well.- Font.BOLD, Font.PLAIN, Font.ITALIC

• Create a Font object by using the “new” operator- Font myFont = new Font(“Helvetica”, Font.BOLD, 12);

- After creating a font, you have to set it before it can be used:g.setFont( myFont);

- You can also do this in line with the setFont() methodg.setFont( new Font(“Helvetica”, Font.BOLD, 12));

• You can also combine styles by adding them together, forexample

Font myFont = new Font(“Helvetica”, Font.BOLD+ Font.ITALIC, 12)

Page 45: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 45

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

//A simple java Applet

public class HelloWorldFont extends Applet {

public void paint(Graphics g){ g. setFont(new Font("Helvetica",

Font. BOLD + Font.ITALIC, 56)); g.drawString("HelloWorld!", 20, 100);}

}

Page 46: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 46

Reading Parameters from HTML File

import java.applet.*;import java.awt.*;//A java Applet with parameters/*<applet code="AppletParameters" width=300

height=300><param name="background" value="0xeeeeee"><param name="foreground" value="0x555555"><param name="message" value="Testing Applet

Parameters"></applet>*/

Page 47: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 47

Reading Parameters from HTML Filepublic class AppletParameters extends Applet {

public void paint(Graphics g) { String background=getParameter("background"); String foreground=getParameter("foreground"); String message=getParameter("message"); setBackground(Color.decode(background)); setForeground(Color.decode(foreground)); Font font=getFont(); FontMetrics fm=getFontMetrics(font); Dimension d=getSize(); int x=(d.width - fm.stringWidth(message))/2; int y=d.height/2; g.drawString(message, x, y); }}

Page 48: Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg

Jan. 2004 48

Java course. Assignment #2, due Oct. 19, 2000

1. Tell the difference between the abstract class and the interface.2. Tell the difference between the method overloading and themethod overriding.3. Read the program on Page 312 and specify what is "upcasting"?4. Read the program on pages 317-318 and specify what I "polymorphism"?5. In the program given on Pages 330-331 (Sandwich.java),create an interface called FastFood (with appropriate method) andchange this program so that it also implements FastFood.6. Create your home page.7. Implement an "applet" which contains two parts:

i) Lamp.htmlii) Lamp.class