Graphics Applets By Mr. Dave Clausen. 2 Applets  A Java application is a stand-alone program with a main method (like the ones we've seen so far)  A.

Slides:



Advertisements
Similar presentations
Graphics Chapter 16.  If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
Advertisements

PHY-102 SAPIntroductory GraphicsSlide 1 Introductory Graphics In this section we will learn how about how to draw graphics on the screen in Java:  Drawing.
LAB SESSION 7 Graphical user interface Applet fundamentals Methods in applets Execution of an applet Graphics class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Outline Graphics Applets Drawing Shapes Components and Containers Images.
Java Graphics Section 1 - Multi-File Graphics Programs Section 2 - The Coordinate System and Graphics Context g Section 3 - The Java Drawing and Painting.
ITEC220 GUI Lecture – Part 2 References  Java Software Solutions,” by Lewis & Loftus  Chapter 7  Chapter 8  Chapter 9  Java Foundations-Introduction.
© 2004 Pearson Addison-Wesley. All rights reserved2-1 Introduction to Graphics The last few sections of each chapter of the textbook focus on graphics.
1 A Simple Applet. 2 Applets and applications An application is an “ordinary” program Examples: Notepad, MS Word, Firefox, Halo, etc. An applet is a Java.
1 Chapter 15 l Basic Figures l Colors l Fonts and Other Text Details Graphics Objects.
©2004 Brooks/Cole Applets Graphics & GUIs. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Graphical Programs Most applications these days are.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Introduction to Java Applets Outline 3.1 Introduction 3.2 Sample Applets from the Java 2.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Topics  Applets  Classes used for graphics Graphics Point Dimension.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Java Applets What is an Applet? How do you create.
1 Applets Chapter 1 To understand:  why applets are used to extend the capabilities of Web pages  how an applet is executed and know about the restrictions.
COMP 14: Applets June 21, 2000 Nick Vallidis. Announcements zP6 is due Friday.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Java Graphics Applets.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Applets and Graphics.
A Simple Applet. Applets and applications An applet is a Java program that runs on a web page –Applets can be run from: Internet Explorer Netscape Navigator.
A Simple Applet.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 5 Graphics. Topics Applets Classes used for graphics –Graphics –Point –Dimension –Color.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Java Programming, 2E Introductory Concepts and Techniques Chapter 2 Creating a Java Application and Applet.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Java Applets What is an Applet? How do you create.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Standard Graphics in Java,
Java Software Solutions Lewis and Loftus Chapter 7 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphics -- Introduction The.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Chapter 17: Applets, Images, and Sound. Objectives Learn about applets Write an HTML document to host an applet Use the init() method Work with JApplet.
Lecture 15: Intro to Graphics Yoni Fridman 7/25/01 7/25/01.
Chapter 10: Applets and Advanced Graphics The Applet Class The Applet Class The HTML Tag The HTML Tag Passing Parameters to Applets Passing Parameters.
Chapter 15Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 15 l Basic Figures l Colors l Fonts and Other Text Details.
Applets & Graphics. Applets programs that run inside a browser Java platform-independence makes applets possible security restrictions: –cannot read or.
Canvas and Graphics CS 21a. 9/26/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L17: Canvas.
Applets Applet is java program that can be embedded into HTML pages. Java applets runs on the java enabled web browsers such as mozilla and internet explorer.
Graphics Copyright © 2015 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming and Data.
1 A Simple Applet. 2 Applets and applications An application is an “ordinary” program Examples: Notepad, MS Word, Firefox, Halo, etc. An applet is a Java.
Swing II. Swing II Topics WindowListener interface WindowListener interface Icons Icons Scrollbars Scrollbars The Graphics class The Graphics class Colors.
Chapter 2: Color and Applets Coming up: Introduction to Graphics.
Graphics & Applets CSC 1051 – Data Structures and Algorithms I
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Introduction to Android (Part.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
Chapter 10: Applets and Advanced Graphics The Applet Class The Applet Class The HTML Tag The HTML Tag Passing Parameters to Applets Passing Parameters.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 A Simple Applet. 2 Applets and applications An applet is a Java program that runs on a web page Applets can be run within any modern browser To run.
CSI 3125, Preliminaries, page 1 AWT. CSI 3125, Preliminaries, page 2 AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based.
Creating a Java Application and Applet
1 Introduction to Graphics b The last one or two sections of each chapter of the textbook focus on graphical issues b Most computer programs have graphical.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Jaeki Song ISQS6337 JAVA Lecture 10 Applets. Jaeki Song ISQS6337 JAVA Applet Applets run within the Web browser environment –Applets bring dynamic interaction.
Please open JCreator and follow these steps: 1)Configure  Options 2)JDK Tools 3)Choose Run Applet from drop-down 4)Click Default, then Edit 5)Click the.
1 Sections 5.1 – 5.2 Digital Image Processing Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
Intro to Graphics from Chapter 2 of Java Software Solutions
Graphics Applets By Mr. Dave Clausen
Chapter 02 Data and Expressions.
Object Oriented Programming
CSC 1051 – Data Structures and Algorithms I
Graphics Applets By Mr. Dave Clausen
Graphics -- Introduction
Outline Character Strings Variables and Assignment
ITEC220 GUI Lecture – Part 2 References
Presentation transcript:

Graphics Applets By Mr. Dave Clausen

2 Applets  A Java application is a stand-alone program with a main method (like the ones we've seen so far)  A Java applet is a program that is intended to transported over the Web and executed using a web browser  An applet also can be executed using the Applet Viewer tool of the Java Software Development Kit  An applet doesn't have a main method  Instead an applet uses public void init() method  Applets can contain: Methods you define Variables and constants Decisions, loops, and arrays

3 Create an Applet  Use JCreator to create the java and html codes Write applet source code in Java  Save with. java file extension Compile applet into bytecode Write HTML document  Save with.html or.htm file extension  Include a statement to call the compiled Java class  To “run” the applet in JCreator Compile the java code Execute the html code to view the applet in the Applet Viewer  Or load HTML document into a Web browser When you make changes, save the java code, recompile the java code, and refresh the browser.

4 Inheritance and bytecode  The class that defines an applet extends the Applet class  This makes use of inheritance.  An applet is embedded into an HTML file using a tag that references the bytecode (.class) file of the applet class  The bytecode version of the program is transported across the web and executed by a Java interpreter that is part of the browser

5 HTML Comments  Comments begin with <!- - (no spaces between)  Comments end with - -> <!--******************************************************************** * * Mr. Clausen 9999 * * * Program Move Circle Applet Animation * * * AP Computer Science Java Period ? * * * Starting Date: 5/?/200? Due Date: 5/?/200? * * * This program will animate a circle in a Java Applet * * Don't forget to include comments describing your applet and * * what exactly it does. * ********************************************************************-->

6 HTML Template & applet Tag YourLastName FirstName ID# Final Project YourLastName FirstName ID# Final Project An HTML Template For Graphics Programs

7 Applet Class Methods  Our Java Source code public class needs to include extends Applet (for example) public class MoveCircle extends Applet  Applet class methods Inherited from the Applet Class Automatically Invoked by the Web browser when the browser runs the applet These methods don’t have to be included in your applet unless you wish to override the methods in the parent class. public void init() public void start() public void stop() public void destroy()

8 Applet method Execution  init() method Executes when a Web page containing an Applet is loaded Or when running appletviewer command  start() method Executes after init() method Executes again every time the applet becomes active after it has been inactive  stop() method Invoked when user leaves Web page  destroy() method Called when user closes browser or Applet Viewer Releases any resources Applet might have allocated

9 Applet Life Cycle

10 Overriding applet Methods  Overriding a method means Replace original version (the inherited version)  Advanced programmers may choose to override the stop () and destroy () methods We will not override them  We will override the init () method To resize our applet To set the background color For example: public void init() { //Set the size of the applet panel resize(760, 520); setBackground (Color.white); }

11 Additional Applet Methods  There are nearly 200 additional methods Manipulate components within Japplets or Applets We are not using apple components in our programs Components include  Buttons  Labels and  Text Fields Read definitions at Web site

12 Applet paint Method  There are several other special methods that serve specific purposes in an applet.  The paint method, for instance, is executed automatically and is used to draw the applet’s contents  The paint method accepts a parameter that is an object of the Graphics class public void paint(Graphics g)  A Graphics object defines a graphics context on which we can draw shapes and text  The Graphics class has several methods for drawing shapes

13 paint() Method  paint() method Runs when Java displays the applet We will write own method to override the default method Executes automatically every time someone  Minimizes, maximizes, or resizes Applet Viewer window or browser window Method header  public void paint(Graphics g)

14 Drawing Shapes  Let's explore some of the methods of the Graphics class that draw shapes in more detail  A shape can be filled or unfilled, depending on which method is invoked  The method parameters specify coordinates and sizes  Recall that the Java coordinate system has the origin in the top left corner  Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle  An arc can be thought of as a section of an oval

15 Coordinate Systems  Each pixel can be identified using a two-dimensional coordinate system  When referring to a pixel in a Java program, we use a coordinate system with the origin in the top-left corner Y X(0, 0) (112, 40)

16 Drawing a Line X Y g.drawLine (10, 20, 150, 45); g.drawLine (150, 45, 10, 20); or

17 Drawing a Rectangle X Y g.drawRect (50, 20, 100, 40);

18 Drawing an Oval X Y g.drawOval (175, 20, 50, 80); bounding rectangle

19 Shape Methods Summary clearRectclearRect(int x, int y, int width, int height) Clears the specified rectangle by filling it with the background color of the current drawing surface. draw3DRectdraw3DRect(int x, int y, int width, int height, boolean raised) Draws a 3-D highlighted outline of the specified rectangle. drawArcdrawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws the outline of a circular or elliptical arc covering the specified rectangle. drawLinedrawLine(int x1, int y1, int x2, int y2) Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. drawOvaldrawOval(int x, int y, int width, int height) Draws the outline of an oval. drawPolygondrawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws a closed polygon defined by arrays of x and y coordinates. drawPolygondrawPolygon(Polygon p) Draws the outline of a polygon defined by the specified Polygon object.Polygon drawRectdrawRect(int x, int y, int width, int height) Draws the outline of the specified rectangle. drawRoundRectdrawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Draws an outlined round-cornered rectangle using this graphics context's current color. drawStringdrawString(String str, int x, int y) Draws the text given by the specified string, using this graphics context's current font and color.String

20 Shape Methods Summary 2 drawStringdrawString(String str, int x, int y) Draws the text given by the specified string, using this graphics context's current font and color.String fill3DRectfill3DRect(int x, int y, int width, int height, boolean raised) Paints a 3-D highlighted rectangle filled with the current color. fillArcfillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Fills a circular or elliptical arc covering the specified rectangle. fillOvalfillOval(int x, int y, int width, int height) Fills an oval bounded by the specified rectangle with the current color. fillPolygonfillPolygon(int[] xPoints, int[] yPoints, int nPoints) Fills a closed polygon defined by arrays of x and y coordinates. fillPolygonfillPolygon(Polygon p) Fills the polygon defined by the specified Polygon object with the graphics context's current color.Polygon fillRectfillRect(int x, int y, int width, int height) Fills the specified rectangle. fillRoundRectfillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Fills the specified rounded corner rectangle with the current color.

21 Drawing Arcs  drawArc() method arguments x-coordinate of upper-left corner of imaginary rectangle that represents bounds of imaginary circle that contains arc y-coordinate of same point Width of imaginary rectangle that represents bounds of imaginary circle that contains arc Height of same imaginary rectangle Beginning arc position Arc angle  drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) drawArc Draws the outline of a circular or elliptical arc covering the specified rectangle.

22 Arc Angles

23 fillArc method  fillArc() method Creates a solid arc  Two straight lines are drawn from the arc endpoints to the center of an imaginary circle whose perimeter the arc occupies.  fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) fillArc Fills a circular or elliptical arc covering the specified rectangle

24 Polygons  drawPolygon() method Draws complex shapes Requires three arguments  An integer array that holds the x-coordinate positions  A second array that holds the corresponding y- coordinate positions  The number of pairs of points to connect  drawPolygon(int[ ] xPoints, int[ ] yPoints, int nPoints) drawPolygon Draws a closed polygon defined by arrays of x and y coordinates.

25 fillPolygon Method  fillPolygon() method Draws a solid shape If the beginning and ending points are not identical  The two endpoints will be connected by a straight line before polygon is filled with color fillPolygon(int[] xPoints, int[] yPoints, int nPoints ) fillPolygon Fills a closed polygon defined by arrays of x and y coordinates.

26 clearRect method  clearRect(int x, int y, int width, int height) clearRect  Clears the specified rectangle by filling it with the background color of the current drawing surface. Appears empty or “clear”  We can use clearRect to erase individual items or the entire background scene if your animation has more than one background scene Much like the way we used cleardevice( ) in C++

27 Color  A Java programmer can control the color of images by using the Color class.  The Color class is included in the package java.awt.  The Color class provides the class constants shown in Table  The Graphics class includes two methods for examining and modifying an image's color (Table 19-3).

28 Color Constants Table 19-2: Color Class Constants

29 Color Methods The Graphics class includes two methods for examining and modifying an image's color (Table 19-3) Using a predefined color g.setColor (Color.red); // red is a method of the color class

30 Create Your Own Colors  Every color can be represented as a mixture of the three additive primary colors Red, Green, and Blue  In Java, each color is represented by three numbers between 0 and 255 that collectively are called an RGB value  A color is defined in a Java program using an object created from the Color class

31 The Color Class  The Color class contains several static predefined colors. Here are a few of the color constants with their RGB values. Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, , 200, 0 255, 255, , 255, 0

32 How To Create Your Own Colors  Java allows the programmer finer control over colors by using RGB (red/green/blue) values.  In this scheme, there are: 256 shades of red 256 shades of green 256 shades of blue  The programmer "mixes" a new color by selecting an integer from 0 to 255 for each color and passing these integers to a Color constructor as follows: new Color (,, )

33 The next code segment shows how to create a random color with RGB values: // Create a random color from randomly generated RGB values int r = (int) (Math.random() * 256); int g = (int) (Math.random() * 256); int b = (int) (Math.random() * 256); Color randomColor = new Color (r, g, b); Create Random Colors

34 Custom Color Examples  Examples of creating and instantiating custom colors Color myGreen = new Color (0, 204, 0); Color myPurple = new Color (153, 0, 150); Color myBrown = new Color (166, 124, 82); Color myOrange = new Color (251, 136, 93);  Using a predefined color g.setColor (Color.red); // red is a method of the color class  Using your custom color g.setColor (myGreen);

35 The Color Class  Every drawing surface has a background color setBackground (Color.white);  Every graphics context has a current foreground color g.setColor (Color.blue);  Both can be set  See Snowman.java and Snowman.htmlSnowman.java Snowman.html  Before starting animation, experiment with drawing shapes in a “still life” using Snowman.java as an example in a “paint” method.

36 Text Properties  A text image has several properties, as shown in Table 19-8 below.  These are set by adjusting the color and font properties of the graphics context in which the text is drawn.

37 Text Properties The Font Class  An object of class Font has three basic properties:  a name  a style  and a size  The following code creates one Font object with the properties Courier bold 12 and another with the properties Arial bold italic 10:  Use descriptive names for your fonts as illustrated below. Font courierBold12 = new Font("Courier", Font.BOLD, 12); Font arialBoldItalic10 = new Font("Arial", Font.BOLD + Font.ITALIC, 10);

38 Text Properties  The Font constants PLAIN, BOLD, and ITALIC define the font styles.  The font size is an integer representing the number of points, where one point equals 1/72 of an inch.  The available font names depend on your particular computer platform.  To see what they are, run the code segment: String fontNames[] = Toolkit.getDefaultToolkit().getFontList(); int i; for (i = 0; i < fontNames.length; i++) System.out.println (fontNames[i]);

39 Text Properties  The code:  Declares the variable fontNames as an array of strings.  Runs the Toolkit class method getDefaultToolkit, which returns the default toolkit for the particular computer platform.  Runs the method getFontList on the toolkit. This method returns a list of the available font names.  Sets the array fontNames to this list.  Executes a loop that displays the contents of fontNames in the terminal window.

40 Text Properties  Table 19-9 lists the principal font methods:

41 Text Properties  Setting the Color and Font Properties of Text  Assume that we want to display the text "Hello world!" in green with the font Courier bold 14. The following code would do this:  Changing the font and color of a graphics context affects all subsequent graphics operations in that context but does not alter the font or color of existing images. Font ourFont = new Font ("Courier", Font.BOLD, 14); Color ourColor = Color.GREEN; Graphics g = getGraphics(); g.setColor (ourColor); g.setFont (ourFont); g.drawString ("Hello world!", 100, 100);

42 Applet Methods Review  In previous examples we've used the paint method of the Applet class to draw on an applet  The Applet class has several methods that are invoked automatically at certain points in an applet's life  The init method, for instance, is executed only once when the applet is initially loaded  The start and stop methods are called when the applet becomes active or inactive  The Applet class also contains other methods that generally assist in applet processing

43 repaint() Method  repaint() method We don’t call the paint() method directly. We call the repaint() method when the window needs to be updated, perhaps with new images. The repaint() method calls another method named update() which in turn calls the paint() method. Creates Graphics object

44 Graphical Objects  Any object we define by writing a class can have graphical elements  The object must simply obtain a graphics context (a Graphics object) in which to draw  An applet can pass its graphics context to another object just as it can any other parameter  See LineUp.javaLineUp.java  See StickFigure.javaStickFigure.java  See LineUp.htmlLineUp.html

45 Mouse Events  Events related to the mouse are separated into mouse events and mouse motion events  Mouse Events: mouse pressed – the mouse button is pressed down mouse released – the mouse button is released mouse clicked – the mouse button is pressed down and released without moving the mouse in between mouse entered – the mouse pointer is moved onto (over) a component mouse exited – the mouse pointer is moved off of a component

46 Mouse Events  Mouse Motion Events: mouse moved – the mouse is moved mouse dragged – the mouse is dragged  To satisfy the implementation of a listener interface, empty methods must be provided for unused events See Documentation for MouseEvent Listener Class MouseEvent

47 Key Events  A key event is generated when a keyboard key is pressed  Constants in the KeyEvent class can be used to determine which key was pressed  The KeyListener interface contains three methods, representing three events: key pressed – a key is pressed key released – a key is released key typed – called when a pressed key produces a key character  See Direction.java and Direction.html Direction.javaDirection.html  See DirectionPanel.java DirectionPanel.java

48 The Direction Program See Documentation for KeyEvent Fields

49 Animations  An animation is a series of images that gives the appearance of movement (24 frames per second)  To create the illusion of movement, we use a timer to change the scene after an appropriate delay  The Timer class of the javax.swing package represents a component, even though it has no visual representation  A Timer object generates an action event at specified intervals

50 Animations  The start and stop methods of the Timer class start and stop the timer  The delay can be set using the Timer constructor or using the setDelay method  See Rebound.java (page 496) Rebound.java  See ReboundPanel.java (page 497) ReboundPanel.java

51 The Rebound Program

52 Sources  Java Software Solutions  by Lewis and Loftus  Addison-Wesley  Fundamentals of Java Second Edition  by Lambert and Osborne  South-Western  Java Programming (versions 1, 2, & 4)  by Joyce Farrell  Thomson