Chapter 2 - Using Objects

Chapter 2 - Using Objects

Chapter 2 U s ing Objects Chapter Goals To learn about variables To understand the concepts of classes and objects To be able to

call methods To learn about arguments and return values To be able to browse the API documentation To implement test programs

To understand the difference between objects and object references To write programs that display simple shapes Objects and Classes Each part a home builder uses, such as a furnace or a water heater, fulfills a particular function. Similarly, you build programs from objects, each of which has a particular behavior.

In Java, you build programs for objects. Each object has certain behaviors. You can manipulate the object to get certain effects. U sing Objects Object: an entity in your program that you can manipulate by calling one or more of its methods. Method: consists of a sequence of instructions that can access the data of an object. You do not know what the instructions are You do know that the behavior is well defined

System.out has a println method You do not know how it works What is important is that it does the work you request of it Figure 1 Representation of the System.out Object U sing Objects You can think of a water heater as an object that can carry

out the "get hot water" method. When you call that method to enjoy a hot shower, you don't care whether the water heater uses gas or solar power. C las s es A class describes a set of objects with the same behavior. Some string objects "Hello World" "Goodbye" "Mississippi" You can invoke the

same methods on all strings. System.out is a member of the PrintStream class that writes to the console window. You can construct other objects of PrintStream class that write to different destinations. All PrintStream objects have methods println and print. C las s es Objects of the PrintStream class have a completely different behavior than the objects of the String class. Different classes have different responsibilities

A string knows about the letters that it contains A string doesn't know how to send itself to a console window or file. All objects of the Window class share the same behavior. Self Check 2.1 In Java, objects are grouped into classes according to their behavior. Would a window object and a water heater object belong to the same class or to different classes? Why? Answer: Objects with the same behavior belong to the same class. A window lets in light while protecting a room from the outside wind and heat

or cold. A water heater has completely different behavior. It heats water. They belong to different classes. Self Check 2.2 Some light bulbs use a glowing filament, others use a fluorescent gas. If you consider a light bulb a Java object with an "illuminate" method, would you need to know which kind of bulb it is? Answer: When one calls a method, one is not concerned with how it does its job. As long as a light bulb illuminates a room, it doesn't matter to the occupant how the photons are produced. Self Check 2.3

What actually happens when you try to call the following? "Hello, World".println(System.out); Answer: When you compile the program, you get an error message that the String class doesnt have a println method. Variables Use a variable to store a value that you want to use later To declare a variable named width int width = 20; Like a variable in a computer program, a parking space has an identifier

and a contents. Syntax 2.1 Variable Declaration Variables A variable is a storage location Has a name and holds a value When declaring a variable, you usually specify an initial value. When declaring a variable, you also specify the type of its values. Variable declaration: int width = 20: width is the name

int is the type 20 is the initial value Each parking space is suitable for a particular type of vehicle, just as each variable holds a value of a particular type. Variable Declarations Types Use the int type for numbers that cannot have a fractional part. int width = 20;

Use the double type for floating point numbers. double milesPerGallon = 22.5; Numbers can be combined by arithmetic operators such as +, -, and * Another type is String String greeting = "Hello"; A type specifies the operations that can be carried out with its values. You can multiply the value width holds by a number You can not multiply greetings by a number. N am es

Pick a name for a variable that describes its purpose. Rules for the names of variables, methods, and classes: Must start with a letter or the underscore (_) character, and the remaining characters must be letters, numbers, or underscores. Cannot use other symbols such as ? or % or a space Use uppercase letters to denote word boundaries, as in milesPerGallon. (Called camel case) Names are case sensitive You cannot use reserved words such as double or class

By Java convention: variable names start with a lowercase letter. class names start with an uppercase letter. Variable Names in Java C om m ents Use comments to add explanations for humans who read your code. double milesPerGallon = 33.8; // The average fuel efficiency of new U.S. cars in 2011

The compiler does not process comments It ignores everything from a // delimiter to the end of the line. For longer comment, enclose it between /* and */ delimiters. The compiler ignores these delimiters and everything in between. Example of longer comments /* In most countries, fuel efficiency is measured in liters per hundred kilometer. Perhaps that is more usefulit tells you how much gas you need

to purchase to drive a given distance. Here is the conversion formula. */ double fuelEfficiency = 235.214583 / milesPerGallon A s s ig nm ent Use the assignment operator (=) to change the value of a variable. You have the following variable declaration int width = 10; To change the value of the variable, assign the new value

width = 20; Figure 2 Assigning a New Value to a Variable A s s ig nm ent It is an error to use a variable that has never had a value assigned to it: int height; int width = height; // ERROR - uninitialized variable height The compiler will complain about an "uninitialized variable" Figure 3 An Uninitialized Variable

Remedy: assign a value to the variable before you use it. int height = 20; int width = height; // OK All variables must be initialized before you access them. A s s ig nm ent The right-hand side of the = symbol can be a mathematical expression: width = height + 10; This means

1. compute the value of height + 10 2. store that value in the variable width width = width + 10 The assignment operator = does not denote mathematical equality. Figure 4 Executing the Statement width = width + 10 Syntax 2.2 Assignment Self Check 2.4 What is wrong with the following variable declaration?

int miles per gallon = 39.4 Answer: There are three errors: 1. You cannot have spaces in variable names. 2. The variable type should be double because it holds a fractional value. 3. There is a semicolon missing at the end of the statement. Self Check 2.5 Declare and initialize two variables, unitPrice and quantity, to contain the unit price of a single item and the number of items purchased. Use reasonable initial values.

Answer: double unitPrice = 1.95; int quantity = 2; Self Check 2.6 Use the variables declared in Self Check 4 to display the total purchase price. Answer: System.out.print("Total price: "); System.out.println(unitPrice * quantity); Self Check 2.7

What are the types of the values 0 and "0"? Answer: int and String Self Check 2.8 Which number type would you use for storing the area of a circle? Answer: double Self Check 2.9 Which of the following are legal identifiers?

Greeting1 g void 101dalmatians Hello, World Answer: Only the first two are legal identifiers. Self Check 2.10

Declare a variable to hold your name. Use camel case in the variable name. Answer: String myName = "John Q. Public"; Self Check 2.11 Is 12 = 12 a valid expression in the Java language? Answer: No, the left-hand side of the = operator must be a variable. Self Check 2.12 How do you change the value of the greeting variable to "Hello, Nina!"?

Answer: greeting = "Hello, Nina!"; Note that String greeting = "Hello, Nina!"; is not the right answerthat statement declares a new variable Self Check 2.13 How would you explain assignment using the parking space analogy? Answer: Assignment would occur when one car is replaced by another in the parking space.

Calling Methods You use an object by calling its methods. All objects of a given class share a common set of methods. The PrintStream class provides methods for its objects such as: println print The String class provides

methods String greeting = Hello, World!; int numberOfCharacters = greeting.length(); that you can apply toUpperCase Example: to all String river = Mississippi; String String bigRiver = river.toUpperCase(); objects.

Example: length The Public Interface of a Cla ss The controls of a car form its public interface. The private implementation is under the hood. The String class declares many other methods besides the length and toUpperCase methods. Collectively, the methods form the public interface of the class. The public interface of a class specifies what you can do with its objects.

The hidden implementation describes how these actions are carried out. A Representation of Two S t r i n g Objects Each String object stores its own data. Both objects support the same set of methods. Those methods form the public interface Public interface is specified by the String class. Method Arguments Most methods require values that give details about the work that the method needs to do.

You must supply the string that should be printed when you call the println method. The technical term for method inputs: arguments. The string greeting is an argument of this method call: System.out.println(greeting); Figure 6 Passing an Argument to the println Method Method Arguments At this tailor shop, the customer's measurements and the fabric are the arguments of the sew method. The return

value is the finished garment. Method Arguments Some methods require multiple arguments. Other methods don't require any arguments at all. Example: the length method of the String class All the information that the length method requires to do its job is stored in the object Figure 7 Invoking the length Method on a String Object Return Values

Some methods carry out an action for you. Example: println method Other methods compute and return a value. Example: the String length method returns a value: the number of characters in the string. You store the return= value in a variable: int can

numberOfCharacters greeting.length() The return value of a method is a result that the method has computed. Return Values You can also use the return value of one method as an argument of another method: System.out.println(greeting.length()); The method call greeting.length() returns a value - the integer 13. The return value becomes an argument of the println method.

Figure 8 Passing the Result of a Method Call to Another Method Return Values - r e p l a c e method Example: assume String river = "Mississippi"; Then the statement river = river.replace("issipp", "our"); Constructs a new String by Replacing all occurrences of "issipp" in"Mississippi" with "our"

Returns the constructed String object "Missouri" And saves the return value in the same variable You could pass the return value to another System.out.println(river.replace("issipp", "our")) method: Return Value - r e p l a c e method - Continued The method call river.replace("issipp", "our"))

Is invoked on a String object: "Mississippi" Has two arguments: the strings "issipp" and "our" Returns a value: the string "Missouri" Figure 9 Calling the replace Method Method Arguments and Return Values Method Declaration To declare a method in a class, specify

The types of the arguments The return value Example: public int length() There are no arguments The return value has the type int Method Declaration - continued Example: public String replace(String target, replacement)

Has two arguments, target and replacement Both arguments have type String The returned value is another string Example: public void println(String output) Has an argument of type String No return value Uses the keyword void String Method Declaration

A class can declare two methods with the same name and different argument types. The PrintStream class declares another println method public void println(int output) Used to print an integer value The println name is overloaded because it refers to more than one method. Self Check 2.14 How can you compute the length of the string "Mississippi"?

Answer: river.length() or "Mississippi".length() Self Check 2.15 How can you print out the uppercase version of "Hello, World!"? Answer: System.out.println(greeting.toUpperCase()); Or System.out.println("Hello, World!".toUpperCase());

Self Check 2.16 Is it legal to call river.println()? Why or why not? Answer: It is not legal. The variable river has type String. The println method is not a method of the String class. Self Check 2.17 What are the arguments in the method call river.replace("p", "s")? Answer: The arguments are the strings "p" and "s".

Self Check 2.18 What is the result of the call river.replace("p", "s"), where river is "Mississippi"? Answer: "Missississi" Self Check 2.19 What is the result of the call greeting.replace("World", "Dave").length(), where greeting is "Hello, World!"? Answer: 12

Self Check 2.20 How is the toUpperCase method declared in the String class? Answer: As public String toUpperCase(), with no argument and return type String. Constructing Objects Objects of the Rectangle class describe rectangular shapes. Constructing Objects The Rectangle object is not a rectangular

shape. It is an object that contains a set of numbers. The numbers describe the rectangle Each rectangle is described by: The x- and y-coordinates of its top-left corner Its width And its height. Constructing Objects In the computer, a Rectangle object is a block of memory that holds four numbers.

Constructing Objects Use the new operator, followed by a class name and arguments, to construct new objects. new Rectangle(5, 10, 20, 30) Detail: 1. The new operator makes a Rectangle object 2. It uses the parameters (in this case, 5, 10, 20, and 30) to initialize the data of the object 3. It returns the object The process of creating a new object is called construction.

The four values 5, 10, 20, and 30 are called the construction arguments. Usually the output of the new operator is stored in a variable: Rectangle box = new Rectangle(5, 10, 20, 30); Additional constructor new Rectangle() Syntax 2.3 Object Construction Self Check 2.21 How do you construct a square with center (100, 100) and side length 20?

Answer: new Rectangle(90, 90, 20, 20) Self Check 2.22 Initialize the variables box and box2 with two rectangles that touch each other. Answer: Rectangle box = new Rectangle(5, 10, 20, 30);

Rectangle box2 = new Rectangle(25, 10, 20, 30); Self Check 2.23 The getWidth method returns the width of a Rectangle object. What does the following statement print? System.out.println(new Rectangle().getWidth()); Answer: 0 Self Check 2.24 The PrintStream class has a constructor whose argument is the name of a file. How do

you construct a PrintStream object with the construction argument "output.txt"? Answer: new PrintStream("output.txt"); Self Check 2.25 Write a statement to save the object that you constructed in Self Check 23 in a variable. Answer: PrintStream out = new PrintStream("output.txt"); Accessor and Mutator Methods Accessor method: does not change the internal data of the object on

which it is invoked. Returns information about the object Example: length method of the String class Example: double width = box.getWidth(); Mutator method: changes the data of the object box.translate(15, 25); The top-left corner is now at (20, 35). Self Check 2.26 What does this sequence of statements print?

Rectangle box = new Rectangle(5, 10, 20, 30); System.out.println("Before: " + box.getX()); box.translate(25, 40); System.out.println("After: " + box.getX()); Answer: Before: 5 After: 30 Self Check 2.27 What does this sequence of statements print? Rectangle box = new Rectangle(5, 10, 20, 30);

System.out.println("Before: " + box.getWidth()); box.translate(25, 40); System.out.println("After: " + box.getWidth()); Answer: Before: 20 After: 20 Moving the rectangle does not affect its width or height. You can change the width and height with the setSize method. Self Check 2.28 What does this sequence of statements print?

String greeting = "Hello"; System.out.println(greeting.toUpperCase()); System.out.println(greeting); Answer: HELLO hello Note that calling toUpperCase doesn't modify the string. Self Check 2.29 Is the toUpperCase method of the String class an accessor or a mutator?

Answer: An accessor it doesn't modify the original string but returns a new string with uppercase letters. Self Check 2.30 Which call to translate is needed to move the box rectangle so that its top-left corner is the origin (0, 0)? Answer: box.translate(-5, -10), provided the method is called immediately after storing the new rectangle into box. The API Documentation

API: Application Programming Interface API documentation: lists classes and methods of the Java library Application programmer: A programmer who uses the Java classes to put together a computer program (or application) Systems Programmer: A programmer who designs and implements library classes such as PrintStream and Rectangle http://docs.oracle.com/javase/7/docs/api/index.html Browsing the API Documentation Figure 13 The API Documentation of the Standard Java Library

Locate Rectangle link in the left pane Click on the link The right pane shows all the features of the Rectangle class Browsing the API Documentation Method Summary Figure 14 The Method Summary for the Rectangle Class

The API documentation for each class has A section that describes the purpose of the class Summary tables for the constructors and methods Clicking on a method's link leads to a detailed description of the method Browsing the API Documentation The detailed description of a method shows: The action that the method carries out The types and names of the parameter variables that receive the

arguments when the method is called The value that it returns (or the reserved word void if the method doesn't return any value). Packag es Java classes are grouped into packages. The Rectangle class belongs to the package java.awt. To use the Rectangle class you must import the import java.awt.Rectangle; package: Put the line at the top of your program.

You don't need to import classes in the java.lang package such as String and System. Syntax 2.4 Importing a Cla ss from a Package Self Check 2.31 Look at the API documentation of the String class. Which method would you use to obtain the string "hello, world!" from the string "Hello, World!"? Answer: toLowerCase

Self Check 2.32 In the API documentation of the String class, look at the description of the trim method. What is the result of applying trim to the string " Hello, Space ! "? (Note the spaces in the string.) Answer: "Hello, Space !" only the leading and trailing spaces are trimmed. Self Check 2.33 Look into the API documentation of the Rectangle class. What is the difference between the methods void translate(int x, int y) and void setLocation(int x, int y)?

Answer: The arguments of the translate method tell how far to move the rectangle in the x- and y-directions. The arguments of the setLocation method indicate the new x- and y-values for the top-left corner. For example, box.translate(1, 1) moves the box one pixel down and to the right. box.setLocation( 1, 1) moves box to the top-left corner of the screen. Self Check 2.34 The Random class is declared in the java.util package. What do you need to do in order to use that class in your program?

Answer: Add the statement import java.util.Random; at the top of your program. Self Check 2.35 In which package is the BigInteger class located? Look it up in the API documentation. Answer: In the java.math package Implementing a Test Program

A test program verifies that methods behave as expected. Steps in writing a tester class 1. Provide a tester class. 2. Supply a main method. 3. Inside the main method, construct one or more objects. 4. Apply methods to the objects. 5. Display the results of the method calls. 6. Display the values that you expect to get. Implementing a Test Program Code to test the behavior of the translate method Rectangle box = new Rectangle(5, 10, 20, 30);

// Move the rectangle box.translate(15, 25); // Print information about the moved rectangle System.out.print("x: "); System.out.println(box.getX()); System.out.println("Expected: 20"); Place the code inside the main method of the MoveTester class Determining the expected result in advance is an important part of testing. s ection_7/ MoveTester.java 1 import java.awt.Rectangle;

2 3 public class MoveTester 4 { 5 public static void main(String[] args) 6 { 7 Rectangle box = new Rectangle(5, 10, 20, 30); 8 // Move the rectangle

9 box.translate(15, 25); 10 11 // Print information about the moved 12 rectangle 13 System.out.print("x: "); 14 System.out.println(box.getX()); 15

System.out.println("Expected: 16 System.out.print("y: "); 20"); 17 System.out.println(box.getY()); 18 System.out.println("Expected: 19 } 35"); 20

21 } Program Run: x: 20 Expected: 20 y: 35 Expected: 35 Self Check 2.36 Suppose we had called box.translate(25, 15) instead of box.translate(15, 25). What are the expected outputs?

Answer: x: 30, y: 25 Self Check 2.37 Why doesn't the MoveTester program print the width and height of the rectangle? Answer: Because the translate method doesn't modify the shape of the rectangle. Object References An object variable is a variable whose type is a class

Does not actually hold an object. Holds the memory location of an object Figure 15 An Object Variable Containing an Object Reference Object References Object reference: describes the location of an object After this statement: Rectangle box = new Rectangle(5, 10, 20, 30); Variable box refers to the Rectangle object returned by the new operator The box variable does not contain the object. It refers to the object.

Object References Multiple object variables can refer to the same object: Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; Figure 16 Two Object Variables Referring to the Same Object N um bers Numbers are not objects. Number variables actually store numbers.

Figure 17 A Number Variable Stores a Number Copying Numbers When you copy a number the original and the copy of the number are independent values. int luckyNumber = 13; int luckyNumber2 = luckyNumber; luckyNumber2 = 12; Figure 18 Copying Numbers Copying Object References

When you copy an object reference both the original and the copy are references to the same object Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; box2.translate(15, 25); Figure 19 Copying Object References Self Check 2.38 What is the effect of the assignment greeting2 = greeting? Answer: Now greeting and greeting2 both refer to the same

String object. Self Check 2.39 After calling greeting2.toUpperCase(), what are the contents of greeting and greeting2? Answer: Both variables still refer to the same string, and the string has not been modified. Recall that the toUpperCase method constructs a new string that contains uppercase characters, leaving the original string unchanged.

Mainframe Computer Mainframe Computer Graphical Applications: Frame Windows A graphical application shows information inside a frame. Frame Windows To show a frame: 1. Construct an object of the JFrame class:

JFrame frame = new JFrame(); 2. Set the size of the frame: frame.setSize(300, 400); 3. If you'd like, set the title of the frame: frame.setTitle("An empty Frame"); 4. Set the "default close operation": frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 5. Make the frame visible: frame.setVisible(true);

section_9_1/EmptyFrameViewer.java 1 2 3 4 5 6 7 8 9 10

11 12 13 import javax.swing.JFrame; public class EmptyFrameViewer { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300, 400); frame.setTitle("An empty frame");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ; frame.setVisible(true); } } Figure 20 A Frame Window Drawing on a Component In order to display a drawing in a frame, define a class that extends the JComponent class. Place drawing instructions inside the paintComponent method.

That method is called whenever the component needs to be repainted: public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { Drawing instructions go here } } Classes G r a p h i c s and Graphics2D Graphics class stores the graphics state (such as current color). Graphics2D class has methods to draw shape objects.

Use a cast to recover the Graphics2D object from the Graphics parameter: public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; . . . } }

Classes G r a p h i c s and Graphics2D The draw method of the Graphics2D class draws shapes, such as rectangles, ellipses, line segments, polygons, and arcs: public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { . . . Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); . . .

} } Coordinate System of a Component The origin (0, 0) is at the upper-left corner of the component. The y-coordinate grows downward. Drawing Rectangles We want to create an application to display two rectangles. Figure 2 Drawing Rectangles

section_9_2/RectangleComponent.java 1 2 3 4 5 6 7 8 9 10 11

12 13 14 15 16 17 18 19 20 21 22 23

24 25 26 import import import import /* java.awt.Graphics; java.awt.Graphics2D;

java.awt.Rectangle; javax.swing.JComponent; A component that draws two rectangles. */ public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D

Graphics2D g2 = (Graphics2D) g; // Construct a rectangle and draw it Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); Move rectangle 15 units to the right and 25 units down // box.translate(15, 25); // Draw moved }

} rectangle g2.draw(box); Displaying a Component in a Frame In a graphical application you need: A frame to show the application A component for the drawing. The steps for combining the

two: 1. Construct a frame object and configure it. RectangleComponent component = new RectangleComponent(); 2. Construct an object of your the component class: 3. Add component to the frame:

frame.add(component); 4. Make the frame visible. section_9_3/RectangleViewer.java 1 import javax.swing.JFrame; 2 3 public class RectangleViewer 4 { 5 public static void main(String[] args)

6 { 7 JFrame frame = new JFrame(); 8 frame.setSize(300, 400); 9 frame.setTitle("Two 10 rectangles"); 11 frame.setDefaultCloseOperation(J

12 RectangleComponent component = new Frame.EXIT_ON_CLOSE); 13 RectangleComponent(); frame.add(component); 14 15 frame.setVisible(true); 16 } 17 18 }

Self Check 2.40 How do you display a square frame with a title bar that reads "Hello, World!"? Answer: Modify the EmptyFrameViewer program as follows: frame.setSize(300, 300); frame.setTitle("Hello, World!"); Self Check 2.41 How can a program display two frames at once? Answer: Construct two JFrame objects, set each of their sizes, and

call setVisible(true) on each of them. Self Check 2.42 How do you modify the program to draw two squares? Answer: Rectangle box = new Rectangle(5, 10, 20, 20); Self Check 2.43 How do you modify the program to draw one rectangle and one square? Answer: Replace the call to box.translate(15, 25)

with box = new Rectangle(20, 35, 20, 20); Self Check 2.44 What happens if you call g.draw(box) instead of g2.draw(box)? Answer: The compiler complains that g doesn't have a draw method. Ellips es To construct an ellipse, you specify its bounding box.

Figure 22 An Ellipse and Its Bounding Box To construct an Ellipse: Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, height); Ellips es Ellipse2D.Double is an inner class doesn't matter to us except for the import statement: import java.awt.geom.Ellipse2D; // No .Double To draw the shape: g2.draw(ellipse);

C ircles To draw a circle, set the width and height to the same values: Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter); g2.draw(circle); (x, y) is the top-left corner of the bounding box, not the center of the circle. Lines To draw a line, specify its end points: Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2); g2.draw(segment);

or Point2D.Double from = new Point2D.Double(x1, y1); Point2D.Double to = new Point2D.Double(x2, y2); Line2D.Double segment = new Line2D.Double(from, to); g2.draw(segment); Drawing Text To draw text, use the drawString method Specify the string and the x- and y-coordinates of the basepoint of the first character g2.drawString("Message", 50, 100);

Figure 23 Basepoint and Baseline C olors To draw in color, you need to supply a Color object. Specify the amount of red, green, blue as values between 0 and 255: Color magenta = new Color(255, 0, 255); The Color class declares a variety of colors: Color.BLUE, Color.RED, Color.PINK etc. To draw a shape in a different color First set color in graphics context:

g2.setColor(Color.Red); g2.draw(circle); // Draws the shape in red Colors - continued To color the inside of the shape, use the fill method: g2.fill(circle); // Fills with current color When you set a new color in the graphics context, it is used for subsequent drawing operations. Predefined Colors Color

RGB Value Color.BLACK 0, 0, 0 Color.BLUE 0, 0, 255 Color.CYAN

0, 255, 255 Color.GRAY 128, 128, 128 Color.DARK_GRAY 64, 64, 64 Color.LIGHT_GRAY

192, 192, 192 Color.GREEN 0, 255, 0 Color.MAGENTA 255, 0, 255 Color.ORANGE

255, 200, 0 Color.PINK 255, 175, 175 Color.RED 255, 0, 0 Color.WHITE

255, 255, 255 Color.YELLOW 255, 255, 0 Alien Face Figure 24 An Alien Face The code is on following slides:

section_10/FaceComponent.java 1 2 3 4 5 6 7 8 9 10 11

12 13 14 15 16 17 18 19 20 21 22 23

24 25 26 27 28 29 30 31 32 33 34 35

import import import import import import import /* java.awt.Color; java.awt.Graphics;

java.awt.Graphics2D; java.awt.Rectangle; java.awt.geom.Ellipse2D; java.awt.geom.Line2D; javax.swing.JComponent; A component that draws an alien face */ public class FaceComponent extends JComponent {

public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; // Draw the head Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150); g2.draw(head); // Draw the eyes g2.setColor(Color.GREEN); Rectangle eye = new Rectangle(25, 70, 15, 15); g2.fill(eye); eye.translate(50, 0);

g2.fill(eye); // Draw the mouth Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110); g2.setColor(Color.RED); g2.draw(mouth); Draw the greeting // section_10/FaceViewer.java 1

2 3 4 5 6 7 8 9 10 11 12 13

14 15 16 17 import javax.swing.JFrame; public class FaceViewer { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(150, 250);

frame.setTitle("An Alien Face"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ; FaceComponent component = new FaceComponent(); frame.add(component); frame.setVisible(true); } } Self Check 2.45 Give instructions to draw a circle with center (100, 100) and radius 25.

Answer: g2.draw(new Ellipse2D.Double(75, 75, 50, 50)); Self Check 2.46 Give instructions to draw a letter "V" by drawing two line segments. Answer: Line2D.Double segment1 = new Line2D.Double(0, 0, 10, 30); g2.draw(segment1); Line2D.Double segment2 = new Line2D.Double(10, 30, 20, 0); g2.draw(segment2);

Self Check 2.47 Give instructions to draw a string consisting of the letter "V". Answer: g2.drawString("V", 0, 30); Self Check 2.48 What are the RGB color values of Color.BLUE? Answer: 0, 0, and 255 Self Check 2.49

How do you draw a yellow square on a red background? Answer: First fill a big red square, then fill a small yellow square inside: g2.setColor(Color.RED); g2.fill(new Rectangle(0, 0, 200, 200)); g2.setColor(Color.YELLOW); g2.fill(new Rectangle(50, 50, 100, 100));

Recently Viewed Presentations

  • CSR and the ASEAN Regional Integration Process Outline

    CSR and the ASEAN Regional Integration Process Outline

    Singapore Tripartism Forum (STF) is a regular platform for tripartite partners to table concerns and work together more effectively to overcome the more complex challenges faced by all today. Regular Events . Annual STF Industrial Relations Seminar.
  • Circles Purple template

    Circles Purple template

    Ar ôl hanner tymor byddwch yn gwerthuso eich gwaith gwirfoddol eich gwersi Bagloriaeth Cymru felly bydd rhaid i chi fod wedi gorffen pan ddewch yn ôl i'r ysgol. Siaradwch â Miss Feathers neu Mrs Hawke-Jones os ydych yn poeni na...
  • The Cerebellum

    The Cerebellum

    The Cerebellum SHANDONG UNIVERSITY Liu Zhiyu Position of Cerebellum Situated in the posterior cranial fossa Covered superiorly by the tentorium of cerebellum Position of Cerebellum Gross Appearance of Cerebellum Consists of two cerebellar hemisphere joined by a narrow median vermis...
  • Telecom Forum - Communications Technology Services Presentation

    Telecom Forum - Communications Technology Services Presentation

    Globafone - mobile satellite Pager Services - Amrcn Messaging and USA Mobility Wireless. Key CTS Objectives. Deliver thought leadershipfor the state and all DIR customers. Create and implement solutionsthat reduce costs and maximize productivity.
  • Patterns around us Sat STEM program, Umass Amherst

    Patterns around us Sat STEM program, Umass Amherst

    Euler buckling - instability . Wrinkling on water (Huang) and on flesh (Cerda 03) -force balance (competing forces), show data from PRL 2010, demo skin . Viscous fingering (later here). competition of rates - driving versus viscous diffusion of pressure.
  • Biology Notes Biochemistry Part 1 Pages 16-29

    Biology Notes Biochemistry Part 1 Pages 16-29

    Do unicellular organisms grow and develop? Unicellular organisms only grow Q. Do multi-cellular organisms grow and develop? A. Multi-cellular organisms both grow and develop. 5. All living things need sources of _____ Energy is needed to complete many of life's...
  • Holding the Hope in Healthcare - Oklahoma Department of ...

    Holding the Hope in Healthcare - Oklahoma Department of ...

    Hope. SAMHSA components of Recovery. These are the components and practices that we know work. We have worked hard, with varying degrees of success to get these principles into our current mental health system. Nothing is perfect - but some...
  • McPAT: An Integrated Power, Area, and Timing Modeling ...

    McPAT: An Integrated Power, Area, and Timing Modeling ...

    McPAT: An Integrated Power, Area, and Timing Modeling Framework for Multicore and Manycore Architectures. Runjie Zhang. Dec.3. S. Li et al. in MICRO'09