Applets and Graphics Yangjun Chen Dept Business Computing
Applets and Graphics Yangjun Chen Dept. Business Computing University of Winnipeg Jan. 2004 1
Outline: Applets and Graphics • Applet - Hello. World Applet import statement Hypertext Mark Language (HTML) • Graphic - line, rectangle, polygon, ovals, arcs, color, font Jan. 2004 2
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 it works is by example. • Let’s look at the applet-version of the Hello. World example from the first class in greater detail. Jan. 2004 3
Hello. World Applet • The Hello. World applet: import java. applet. *; import java. awt. *; // A simple Java Applet public class Hello. World extends Applet { public void paint( Graphics g) { g. draw. String(“ Hello. World!”, 20, 10); } } Jan. 2004 4
Hello. World 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 Hello. World. 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 Hello. World. html Jan. 2004 5
Hello. World Applet • Example (Hello. World. html): <HTML> <BODY> <APPLET CODE = Hello. World. class WIDTH = 200 HEIGHT=200> </ APPLET> </BODY> </HTML> URL address: file: //e: /javaprog/Hello. World. html Jan. 2004 6
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(). Jan. 2004 7
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. Jan. 2004 8
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 Applet. Lifecycle extends Applet { String str = ""; public void init() { str += "init; "; } Jan. 2004 9
Life Cycle of an Applet public void start() { str += "start; "; } public void stop() { str += "stop; "; } public void destroy() { System. out. println(str + "destroy; ”); } public void paint(Graphics g) { g. draw. String(str, 10, 25); } } Jan. 2004 10
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 know that we want to use classes that are in the packages java. applet and java. awt. - The java. applet package: contains definitions for the applet class - The java. awt package: contains classes for displaying graphics Jan. 2004 11
import Statements • The “*” acts as a wildcard that will import all of the classes in the package • Difference between this “*” and the one used at a command prompt. - 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 but does not import the subpackages. Jan. 2004 12
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. *; Jan. 2004 13
import Statement Syntax • The form of an import statement is as follows: - import package. Name. *; or import package. Name. class. Name ; 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 the beginning of your program. Jan. 2004 14
Importing Classes • Should you take time to import classes individually or import them as a group? - Importing them as a group does not add any overhead because only the classes that are used in your code are actually 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. Jan. 2004 15
draw. String() method • The draw. String() method belongs to the Graphics class • g is a Graphics object and we want it to execute it’s own draw. String() method. • We also pass it what we want to draw on the screen and where we want the graph to be drawn. • The draw. String() method is defined in the Graphics as follows: Public void draw. String( String s, int x, int y) { Code to draw s on the screen at location x, y } Jan. 2004 16
Where does paint() start? • We are finished with the program, but where does the paint() method invoked? • A lot of actions in a Java program are done behind the scenes and 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 a window, or when you uncover the applet. Jan. 2004 17
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 of keywords that are enclosed between angle brackets, “<“ and “>”: <H 1> • Everything that is not a tag is considered to be plain text and displayed by your browser. • HTML is platform independent. Jan. 2004 18
HTML Tags • HTML tags are case- insensitive, but are usually capitalized to make them stand out. • A tag is enclosed in angle brackets, for example <H 1> is a tag that would make a level 1 heading. To end the level 1 heading we would put in an end tag </H 1>. - Example: <H 1> This is a level one heading </H 1> This would appear on the screen as: This is a level one heading <H 6> This is a level six heading </H 6> Jan. 2004 This is a level one heading 19
HTML Tags • HTML elements can not overlap: - the following is not allowed <H 1>< B> Bold and H 1 overlap - this is illegal</ H 1></ B> • Some elements can also take attributes: - <H 1 ALIGN=“ center”> This is a heading</ H 1> This will center the heading whenever it is possible. Attributes always appear in 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. Jan. 2004 20
HTML Skeleton <HTML> <!- Comment Line. -> <HEAD> <TITLE> This is the document Title</ TITLE> </ HEAD> <BODY> … This is the document text. … </ BODY> </ HTML> Jan. 2004 21
Applet Tag <HTML> <!- Comment Line. -> <HEAD> <TITLE> This is the document Title</ TITLE> </ HEAD> <BODY> … <APPLET CODE=“ Hello. World. class” width= 100 height= 100> </ APPLET> … </ BODY> </ HTML> Jan. 2004 22
Some Common HTML Tags • <BR> - This gives you an end of line • <HR> - Horizontal Rule - draws a horizontal line • <PRE>…</PRE> - Preformatted text - everything between the tags will appear on the web page as it does in your editor. • <A HREF=“ some. URL”> click here</A> - Creates a hyperlink to “some. URL” • <A HREF=“ mailto: name@ company. com”> text to highlight</A> - sends an email to the address given. • <IMG SRC=“ filename. gif”> - displays an image • Jan. <B> BOLD </B> <I> ITALICS </I> 2004 23
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 if no 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” Jan. 2004 24
Graphics • The java. awt package contains all the necessary classes you need to create graphical user interfaces (GUIs). • Most of the graphics operations in Java are methods defined in the Graphics class. • You don’t have to create an instance of the Graphics class because in the applet’s paint() method, a Graphics object is provided for you. By drawing in that object, you draw onto your applet which appears on the screen. • The Graphics class is part of the java. awt package, so make sure you import it into your Java code. Jan. 2004 25 - import java. awt. Graphics;
The Coordinate System • Java’s coordinate system has the origin (0, 0) in the top left corner of the applet. - Positive x values are to the right and positive y values are downward • The coordinate system is represented by pixels. +X (0, 0) - Pixels in Java are integer values only (20, 20) +Y Jan. 2004 (60, 50) 26
Lines • To draw a line onto the screen, use the draw. Line() method: - void draw. Line( int x 1, int y 1, int x 2, int y 2); - This draws a line from the point with coordinates (x 1, y 1) to the point with coordinates (x 2, y 2). - Example: import java. awt. Graphics; public class My. Line extends java. applet. Applet { public void paint( Graphics g) { g. draw. Line( 25, 75, 75); } } - There is no way to change the line thickness in Java. Jan. 2004 So how do we make thicker lines? 27
Rectangles • To draw a rectangle on the screen, use the draw. Rect() method: - void draw. Rect( int x, int y, int width, int height) - This draws an outline of a rectangle with the top left corner of the rectangle having the point (x, y). The size of the rectangle is governed by the width and height arguments. • To fill in the rectangle we would use the method fill. Rect(). This works in the same way as draw. Rect() but fills in the rectangle with the current drawing color. • To change the current drawing color we use the method: - void set. Color( Color c) - The drawing color stays fixed until it is changed by another call to the set. Color() method. Jan. 2004 28
Rectangles • Example: import java. awt. *; public class My. Rect extends java. applet. Applet { public void paint( Graphics g) { g. draw. Rect(20, 60, 60); g. set. Color( Color. red); g. fill. Rect( 120, 60, 60); } } Jan. 2004 29
Rounded Rectangles • These are rectangles with the corners rounded according to the values of the arguments. • Like the rectangle, there are two methods for round rectangles: - void draw. Round. Rect( int x, int y, int width, int height, int arc. Width, int arc. Height) - void fill. Round. Rect( int x, int y, int width, int height, int arc. Width, int arc. Height) Jan. 2004 30
3 D 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 draw 3 DRect( int x, int y, int width, int height, boolean raised) - void fill 3 DRect( 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. Jan. 2004 31
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 straight lines from the first point to the second, to the third and so on. • Once again, there is a draw. Polygon() method and a fill. Poylgon() 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 draw. Polyline() method. Jan. 2004 32
Polygon Using Arrays • Example: import java. awt. Graphics; public class My. Polygon 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. draw. Polygon( exes, whys, pts); } } Jan. 2004 33
Polygons using the Polygon Class • The second way is to use a polygon object to store the individual 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. add. Point( 20, 35); • So we can draw a polygon by passing our Polygon object into the draw. Polygon() or fill. Polygon() method. Jan. 2004 34
Polygons using the Polygon Class • Example: import java. awt. Graphics; import java. awt. Polygon; public class My. Polygon 2 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. draw. Polygon(poly); g. fill. Polygon( poly); } } Jan. 2004 35
Ovals • Ovals are drawn with the draw. Oval() or fill. Oval() methods - void draw. Oval( int x, int y, int width, int height) - void fill. Oval( int x, int y, int width, int height) - This draws an oval within the bounding rectangle specified by the arguments - Example: import java. awt. Graphics; public class My. Oval extends java. applet. Applet { public void paint( Graphics g) { g. draw. Oval( 20, 60, 60); g. fill. Oval( 120, 60, 60); } } Jan. 2004 36
Arcs • An arc is basically part of an oval. • Arcs are drawn using the method: — - void draw. Arc( int x, int y, int width, int height, int start. Angle, int arc. Angle) - void fill. Arc( int x, int y, int width, int height, int start. Angle, int arc. Angle) - This draws an arc within the rectangle specified starting from the start. Angle argument for a duration of arc. Angle. - Example: g. draw. Arc( 10, 100, 80, 45, 210); Jan. 2004 37
Arcs • Example: import java. awt. Graphics; public class My. Arc extends java. applet. Applet { public void paint( Graphics g) { g. draw. Arc( 120, 60, 90, 180); g. fill. Arc( 120, 60, 90, 180); } } Jan. 2004 38
Graphics Example Jan. 2004 import java. awt. *; public class Lamp extends java. applet. Applet{ public void paint( Graphics g) { g. set. Color(Color. red); g. fill. Rect( 0, 250, 290); // lamp platform g. draw. Line( 125, 250, 125, 160); // base of lamp g. draw. Line( 175, 250, 175, 160); g. draw. Arc( 85, 157, 130, 50, - 65, 312); // lamp shade g. draw. Arc( 85, 87, 130, 50, 62, 58); // top & bottom edges g. draw. Line( 85, 177, 119, 89); // lamp shade sides g. draw. Line( 215, 177, 181, 89); g. fill. Arc( 78, 120, 40, 63, - 174); // dots on shade g. fill. Oval( 120, 90, 40); g. fill. Arc( 173, 100, 40, 110, 180); } } 39
Copying areas of the Screen • After drawing things on the screen, you might want to move things around • The copy. Area() method copies a rectangular area of the screen to another area of the screen - void copy. Area( int x, int y, int width, int height, int dx, int dy) - The first four arguments specify the rectangle to copy and dx and dy represent the distance in the x and y direction. - Example g. copy. Area( 0, 0, 100, 0); Jan. 2004 40
Clearing the screen • Now that we have drawn things on the screen, we want to clear them. • The way Java clears the screen is by drawing over it with the background color. • This method is called clear. Rect() - void clear. Rect( int x, int y, int width, int height) - This clears a rectangular area specified by the arguments. Jan. 2004 41
The Color Class • This class contains 13 constant values that can be used: - black, blue, cyan, dark. Gray, green, light. Gray, magenta, orange, pink, red, white, yellow • To address them we have to reference them through the Color class - eg. Color. black - Too set the current color to blue: g. set. Color(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 between 0 and 255, with 0 representing no light. (0, 0, 0) is black Jan. 2004 (128, 128) is medium gray 42
The Color Class • To declare a new color in Java, use the “new” operator - Color my. Color = 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 directly g. set. Color(my. Color); - You can also define the color “on the fly” or in line with the set. Color() method g. set. Color( new Color( 255, 0, 128)); Jan. 2004 43
The Font Class • There are five basic fonts in Java - San. Serif (Helvetica), Serif (Times Roman), Monospaced (Courier), Dialog. Input • There are some constant values associated with the Font class as well. - Font. BOLD, Font. PLAIN, Font. ITALIC • Create a Font object by using the “new” operator - Font my. Font = new Font(“Helvetica”, Font. BOLD, 12); - After creating a font, you have to set it before it can be used: g. set. Font( my. Font); You can also do this in line with the set. Font() method g. set. Font( new Font(“Helvetica”, Font. BOLD, 12)); - • You can also combine styles by adding them together, for example Jan. 2004 Font my. Font = new Font(“Helvetica”, Font. BOLD+ Font. ITALIC, 12) 44
import java. applet. *; import java. awt. *; //A simple java Applet public class Hello. World. Font extends Applet { public void paint(Graphics g) { g. set. Font(new Font("Helvetica", Font. BOLD + Font. ITALIC, 56)); g. draw. String("Hello. World!", 20, 100); } } Jan. 2004 45
Reading Parameters from HTML File import java. applet. *; import java. awt. *; //A java Applet with parameters /* <applet code="Applet. Parameters" width=300 height=300> <param name="background" value="0 xeeeeee"> <param name="foreground" value="0 x 555555"> <param name="message" value="Testing Applet Parameters"> </applet> */ Jan. 2004 46
Reading Parameters from HTML File public class Applet. Parameters extends Applet { public void paint(Graphics g) { String background=get. Parameter("background"); String foreground=get. Parameter("foreground"); String message=get. Parameter("message"); set. Background(Color. decode(background)); set. Foreground(Color. decode(foreground)); Font font=get. Font(); Font. Metrics fm=get. Font. Metrics(font); Dimension d=get. Size(); int x=(d. width - fm. string. Width(message))/2; int y=d. height/2; g. draw. String(message, x, y); } } Jan. 2004 47
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 the method 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 Fast. Food (with appropriate method) and change this program so that it also implements Fast. Food. 6. Create your home page. 7. Implement an "applet" which contains two parts: i) Lamp. html ii) Lamp. class Jan. 2004 48
- Slides: 48