Graphics Applets. By Mr. Dave Clausen

Similar documents
Graphics Applets. By Mr. Dave Clausen

Appendix F: Java Graphics

Appendix F: Java Graphics

Lecture 7 A First Graphic Program And Data Structures & Drawing

Java Applet Basics. Life cycle of an applet:

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

SIMPLE APPLET PROGRAM

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University


Graphics -- To be discussed

9. APPLETS AND APPLICATIONS

Here is a list of a few of the components located in the AWT and Swing packages:

CSC System Development with Java Introduction to Java Applets Budditha Hettige

Java TM Applets. Rex Jaeschke

Unit 7: Event driven programming

public static void main(string[] args) { GTest mywindow = new GTest(); // Title This program creates the following window and makes it visible:

Data Representation and Applets

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

Applets and the Graphics class

Data Representation and Applets

Data Representation and Applets

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

TWO-DIMENSIONAL FIGURES

@Override public void start(stage primarystage) throws Exception { Group root = new Group(); Scene scene = new Scene(root);

Graphics and Java2D. Objectives

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Programming: You will have 6 files all need to be located in the dir. named PA4:

cs Java: lecture #5

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

Chapter 14: Applets and More

8/23/2014. Chapter Topics. Introduction to Applets. Introduction to Applets. Introduction to Applets. Applet Limitations. Chapter 14: Applets and More

Chapter 14: Applets and More

Chapter 7 Applets. Answers

Java - Applets. public class Buttons extends Applet implements ActionListener

Java Coordinate System

AP CS Unit 12: Drawing and Mouse Events

Chapter 3 - Introduction to Java Applets

CS1004: Intro to CS in Java, Spring 2005

Some classes and interfaces used in this chapter from Java s original graphics capabilities and from the Java2D API.

Advanced Internet Programming CSY3020

Graphics and Painting

UNIT -1 JAVA APPLETS

G51PRG: Introduction to Programming Second semester Applets and graphics

MaSH Environment graphics

CSIS 10A Assignment 14 SOLUTIONS

Lab 3: Work with data (IV)

Exam: Applet, Graphics, Events: Mouse, Key, and Focus

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Graphics and Java 2D Introduction OBJECTIVES. One picture is worth ten thousand words.

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Object Orientated Programming in Java. Benjamin Kenwright

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction

China Jiliang University Java. Programming in Java. Java Applets. Java Web Applications, Helmut Dispert

IS311 Programming Concepts. Abstract Window Toolkit (part 1: Drawing Simple Graphics)

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Graphical User Interface (GUI)

Java Applet & its life Cycle. By Iqtidar Ali

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Chapter 12 Advanced GUIs and Graphics

Using Graphics. Building Java Programs Supplement 3G

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY

Variables, Types, and Expressions

Chapter. We've been using predefined classes. Now we will learn to write our own classes to define objects

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Paint Tutorial (Project #14a)

Dr. Hikmat A. M. AbdelJaber

CT 229 Arrays in Java

Part 3: Graphical User Interface (GUI) & Java Applets

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Graphical User Interface (GUI)

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

Goals. Java - An Introduction. Java is Compiled and Interpreted. Architecture Neutral & Portable. Compiled Languages. Introduction to Java

PROGRAMMING LANGUAGE 2

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet

Chapter 3: Inheritance and Polymorphism

Exercise NMCGJ: Animated Graphics

Assignment 2. Application Development

CISC 1600 Lecture 3.1 Introduction to Processing

Course 2DCis: 2D-Computer Graphics with C# Chapter C1: Comments to the Intro Project

IT101. Graphical User Interface

Data Representation and Applets

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

Lecture Static Methods and Variables. Static Methods

Summary. 962 Chapter 23 Applets and Java Web Start

Practice Midterm 1. Problem Points Score TOTAL 50

c.def (pronounced SEE-def) Language Reference Manual

Garfield AP CS. Graphics

Building Java Programs

Objectives. Defining Classes and Methods. Objectives. Class and Method Definitions: Outline 7/13/09

Mobile Systeme Grundlagen und Anwendungen standortbezogener Dienste. Location Based Services in the Context of Web 2.0

Java Programming Lecture 6

Transcription:

Graphics Applets By Mr. Dave Clausen

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 2

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 (.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. 3

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 4

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. * ********************************************************************--> 5

HTML Template & applet Tag <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <title>yourlastname FirstName ID# Final Project</title> </head> <body> <center> <h3>yourlastname FirstName ID# Final Project</h3> <applet code= LastNameFirstNameFP.class" width=760 height=520> </applet> </center> </body> </html> An HTML Template For Graphics Programs 6

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() 7

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 8

Applet Life Cycle 9

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); } 10

Additional Applet Methods There are nearly 200 additional methods Manipulate components within Japplets or Applets We are not using applet components in our programs Components include Buttons Labels and Text Fields Read definitions at http://java.sun.com Web site 11

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 12

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) 13

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 14

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 (0, 0) 112 X 40 (112, 40) Y 15

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

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

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

Drawing a Polygon drawpolygon(int[ ] xpoints, int[ ] ypoints, int npoints) Draws a closed polygon defined by arrays of x and y coordinates. fillpolygon(int[ ] xpoints, int[ ] ypoints, int npoints) Fills a closed polygon defined by arrays of x and y coordinates. fillpolygon example HTML file Java file public class DrawPolygon extends Applet { int[ ] xpoints = {10, 80, 10, 10}; int[ ] ypoints = {120, 160, 200, 120};... public void paint (Graphics g) { g.setcolor (Color.orange); g.fillpolygon (xpoints,ypoints,4); } 19

Shape Methods Summary clearrect(int x, int y, int width, int height) Clears the specified rectangle by filling it with the background color of the current drawing surface. draw3drect(int x, int y, int width, int height, boolean raised) Draws a 3-D highlighted outline of the specified rectangle. drawarc(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. drawline(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. drawoval(int x, int y, int width, int height) Draws the outline of an oval. drawpolygon(int[] xpoints, int[] ypoints, int npoints) Draws a closed polygon defined by arrays of x and y coordinates. drawpolygon(polygon p) Draws the outline of a polygon defined by the specified Polygon object. drawrect(int x, int y, int width, int height) Draws the outline of the specified rectangle. drawroundrect(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. drawstring(string str, int x, int y) Draws the text given by the specified string, using this graphics context's current font and color. 20

Shape Methods Summary 2 drawstring(string str, int x, int y) Draws the text given by the specified string, using this graphics context's current font and color. fill3drect(int x, int y, int width, int height, boolean raised) Paints a 3-D highlighted rectangle filled with the current color. fillarc(int x, int y, int width, int height, int startangle, int arcangle) Fills a circular or elliptical arc covering the specified rectangle. filloval(int x, int y, int width, int height) Fills an oval bounded by the specified rectangle with the current color. fillpolygon(int[] xpoints, int[] ypoints, int npoints) Fills a closed polygon defined by arrays of x and y coordinates. fillpolygon(polygon p) Fills the polygon defined by the specified Polygon object with the graphics context's current color. fillrect(int x, int y, int width, int height) Fills the specified rectangle. fillroundrect(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) 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) 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) 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) Fills a closed polygon defined by arrays of x and y coordinates. 26

clearrect method clearrect(int x, int y, int width, int height) 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 19-2. 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, 255 255, 200, 0 255, 255, 255 255, 255, 0 32

How To Create Your Own Colors Java allows the programmer more refined 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 (<int for red>, <int for green>, <int for blue>) 33

Create Random Colors 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); 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 Both can be set g.setcolor (Color.blue); See Snowman.java and 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

The Font Class Text Properties 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: Font courierbold14= new Font ("Courier", Font.BOLD, 14); Color mygreen= new Color(0, 255, 0); g.setcolor (mygreen); g.setfont (courierbold14); g.drawstring ("Hello world!", 100, 100); 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. 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.java See StickFigure.java See LineUp.html 45

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 private final int SLEEP_TIME = 10; //milliseconds //delay try { } Thread.sleep(SLEEP_TIME); catch(interruptedexception e) { } 46

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 47