Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 6 Graphics.

Slides:



Advertisements
Similar presentations
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
Advertisements

2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Laboratory Study II October, Java Programming Assignment  Write a program to calculate and output the distance traveled by a car on a tank of.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
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?
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.
Java Graphics Section 1 - Multi-File Graphics Programs Section 2 - The Coordinate System and Graphics Context g Section 3 - The Java Drawing and Painting.
Building Java Programs Supplement 3G Graphics Copyright (c) Pearson All rights reserved.
Building Java Programs Supplement 3G Graphics Copyright (c) Pearson All rights reserved.
1 L36 Graphics and Java 2D™ (1). 2 OBJECTIVES  To understand graphics contexts and graphics objects.  To understand and be able to manipulate colors.
Copyright 2008 by Pearson Education Building Java Programs Graphics Reading: Supplement 3G.
1 Chapter 15 l Basic Figures l Colors l Fonts and Other Text Details Graphics Objects.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Topics  Applets  Classes used for graphics Graphics Point Dimension.
Slides prepared by Rose Williams, Binghamton University Chapter 19 Swing II.
May 11, 1998CS102-02Lecture 7-1 More Graphics in Java CS Lecture 7-1 A picture's worth a thousand words.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
Copyright 2008 by Pearson Education Building Java Programs Graphics reading: Supplement 3G videos: Ch. 3G #1-2.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Java Graphics Applets.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
1 Graphical objects We will draw graphics in Java using 3 kinds of objects: DrawingPanel : A window on the screen. Not part of Java; provided by the authors.
Graphics. Graphics Features in Java Topics to be covered Topics to be covered Graphics Basics Graphics Basics Coordinate System Coordinate System Graphics,
Chapter 16: Graphics. Objectives Learn about the paint() and repaint() methods Use the drawString() method to draw String s using various fonts and colors.
Java Software Solutions Lewis and Loftus Chapter 7 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphics -- Introduction The.
1 Graphical User Components (II) Outline JTextArea Creating a Customized Subclass of JPanel JPanel Subclass that Handles Its Own Events Windows: Additional.
2D Graphics: Rendering Details
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 28 - Java Graphics and Java2D Outline 28.1Introduction.
Chapter 28 - Java Graphics and Java2D Outline 28.1Introduction 28.2Graphics Contexts and Graphics Objects 28.3Color Control 28.4Font Control 28.5Drawing.
 Pearson Education, Inc. All rights reserved. 1 Ch 12 Graphics and Java 2D In this chapter you will learn:  To understand graphics contexts.
Copyright 2010 by Pearson Education Building Java Programs Graphics reading: Supplement 3G.
Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 6 Graphics.
Lecture 15: Intro to Graphics Yoni Fridman 7/25/01 7/25/01.
Chapter 15Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 15 l Basic Figures l Colors l Fonts and Other Text Details.
Chapter 7 Graphics. © Daly and Wrigley Objectives Use Graphic Components: ▫ Strings ▫ Lines ▫ Rectangles ▫ Ovals ▫ Arcs Change the color and font of elements.
Graphics & Java 2D Drawing Two Dimensional Shapes Controlling Fonts Controlling Colors.
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 Building Java Programs Supplement 3G: Graphics These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold,
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Merete S COLLEGEFACULTY OF ENGINEERING & SCIENCE Graphics ikt403 – Object-Oriented Software Development.
Building Java Programs Supplement 3G Graphics Copyright (c) Pearson All rights reserved.
Painting (Chapter 12) Java Certification Study Group January 25, 1999 Mark Roth.
Chapter 2: Graphics In Java Basics of classes –instance variables –methods –overriding methods Graphics class (drawing routines) Other classes –Color –Font.
1 Graphics, Fonts and Color Chapter 9. 2 What is in this chapter: l Graphics class and coordinates l graphics primitives (lines,rectangles,ovals and arcs)
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.
CS305j Introduction to Computing Simple Graphics 1 Topic 11 Simple Graphics "What makes the situation worse is that the highest level CS course I've ever.
Introduction to Graphics. Graphical objects To draw pictures, we will use three classes of objects: –DrawingPanel : A window on the screen. –Graphics.
Copyright 2008 by Pearson Education Building Java Programs Graphics reading: Supplement 3G videos: Ch. 3G #1-2.
6.1 Coordinates The screen of a computer is a grid of little squares called pixels. The color of each pixel can be set individually, and drawing on the.
CPCS 391 Computer Graphics Lab One. Computer Graphics Using Java What is Computer Graphics: Computer graphics are graphics created using computers and,
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
Chapter 8 Graphics.
Graphics Chapter 6 Copyright © 2000 W. W. Norton & Company.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 10 Graphics.
4.14 GUI and Graphics Case Study: Creating Simple Drawings (Cont.)
Graphics Chapter 6 Copyright © 2000 W. W. Norton & Company.
CSE 142 Lecture Notes Graphics with DrawingPanel Chapter 3
Building Java Programs
Chapter 8 Graphics.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Graphics Reading: Supplement 3G
Presentation transcript:

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 6 Graphics

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Creating a Drawing Java’s Abstract Window Toolkit (AWT) provides classes and other tools that are used to build programs that have a graphical user interface. This class provides methods for drawing lines, rectangles, ovals, arcs, polygons, and polylines. There’s also a method for displaying text.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 3 Graphics Contexts An instance of the Graphics class is a rectangular area, called a graphics context, that's capable of storing an image. A graphics context consists of many tiny pixels (picture elements), each capable of displaying a single speck of color.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 4 Graphics Contexts An image consisting of black and white pixels:

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 5 A Sample Graphics Context

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 6 Steps in Java code 1.Import the java.awt.* package. 2.Import the jpb.* package. 3.Create an object of type DrawableFrame. 4.Call the show() method with the DrawableFrame object. 5.Call the setSize(int, int) method with the DrawableFrame object – to give the Frame a size that we desire in pixels. 6.Create a graphics context with getGraphicsContext() method of Frame. 7.Call your method to create the drawing with the Graphics variable. 8.Call the repaint() method from the DrawableFrame package to make sure that the user will see the image.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 7 Example import java.awt.*; import jpb.*; public class DrawLine { public static void main(String[] args) { // Create drawable frame DrawableFrame df = new DrawableFrame("Draw Line"); df.show(); df.setSize(150, 150); // Obtain graphics context Graphics g = df.getGraphicsContext(); // Draw line g.drawLine(50, 50, 100, 100); // Repaint frame df.repaint(); }

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 8 drawLine(int x1, int y1, int x2, int y2) drawRect (x, y, width, height) and fillRect (x, y, width, height) drawOval (x, y, width, height) and fillOval (x, y, width, height) Draw3DRect (x, y, width, height) and fill3DRect (x, y, width, height) DrawRoundRect (x, y, width, height, arcWidth, arcHeight) drawArc(int x,int y,int width, int height, int startAngle, int arcAngle) fillRect(int x, int y, int width, int height) drawPolyline (int[] x, int[] y, int N) drawPolygon (int[] x, int[] y, int N) Drawing methods in Graphics class

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 9 drawLine(x1, y1, x2, y2) A line between (x1, y1) to (x2, y2): (x1, y1) (x2, y2)

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 10 An ordinary rectangle: drawRect(x, y, width, height)

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 11 An oval: If the width and height arguments are equal, drawOval and fillOval will draw circles. drawOval(x, y, width, height)

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 12 A rectangle with rounded corners: drawRoundRect(x, y, width, height, arcWidth, arcHeight)

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 13 drawArc(x,y,width,height, startAngle, arcAngle)

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 14 drawPolygon(xCoordinates, yCoordinates, xCoordinates.length); int[] xCoordinates = {0, 100, 200}; int[] yCoordinates = {100, 0, 100}; drawPolygon(xCoordinates, yCoordinates,3);

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 15 drawPolyline(xCoordinates, yCoordinates, xCoordinates.length); int[] xCoordinates = {0, 100, 200}; int[] yCoordinates = {100, 0, 100}; drawPolygon(xCoordinates, yCoordinates,3);

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Drawing in Color Each Graphics object also has a “current color.” All drawing is done in that color until the setColor method is called. When setting the color, we follow the following call: g.setColor(Color.red); // use constant color Or g.setColor(new Color(75, 195, 200 )); //define a new color By default, the drawing color is black.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 17 Color Constants Red GreenBlue NameComponentComponentComponent black blue cyan darkGray gray green lightGray magenta orange pink red white yellow

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 18 Calling the setColor Method Using a constant from the Color class is done by writing the name of the class ( Color ), a dot, and then the name of the constant. A call of setColor that changes the current drawing color to magenta: g.setColor(Color.magenta);

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 19 Define a new Color Java have a number of colors expressed in words such as "red", "green", "blue", etc. Possible number of colors = 256*256*256 Example: Color newColor = new Color(75, 195, 200); cir.setColor(newColor); OR cir.setColor(new Color(75, 195, 200));

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Displaying Text Use drawString method. Example: g.drawString("Java rules!", x, y);

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 21 The Font Class The current font can be changed by calling the setFont method: Before, we have to define a new font, though. Example: Font f = new Font("SansSerif", Font.BOLD, 24); g.setFont(f); or g.setFont(new Font ("SansSerif", Font.BOLD, 24) );

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 22 The Font Class Parameters for Font object constructor. Font name : "Monospaced", "Serif", or "SansSerif". Font style. Possible styles are bold, italic, and plain, represented by the constants Font.BOLD, Font.ITALIC, and Font.PLAIN. Writing Font.BOLD + Font.ITALIC creates a font that’s both bold and italic. Font size. Font sizes are measured in points. (A point is approximately 1/72" or 0.35 mm.)

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 23 DisplayText.java // Displays text in three different colors and styles import java.awt.*; import jpb.*; public class DisplayText { public static void main(String[] args) { // Create drawable frame DrawableFrame df = new DrawableFrame("Display Text"); df.show(); df.setSize(210, 85); // Obtain graphics context Graphics g = df.getGraphicsContext();

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 24 // Display "Monospaced Bold" g.setColor(Color.red); g.setFont(new Font("Monospaced", Font.BOLD, 20)); g.drawString("Monospaced Bold", 15, 25); // Display "SansSerif Italic" g.setColor(Color.green); g.setFont(new Font("SansSerif", Font.ITALIC, 20)); g.drawString("SansSerif Italic", 15, 50); // Display "Serif Plain" g.setColor(Color.blue); g.setFont(new Font("Serif", Font.PLAIN, 20)); g.drawString("Serif Plain", 15, 75); // Repaint frame df.repaint(); }

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Combining Text with Graphics Combining text with graphics is easy, because the graphics methods (such as drawLine and drawRect ) and the text method ( drawString ) all operate on a Graphics object.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 26 Program: Displaying a Stop Sign The StopSign program displays a stop sign:

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 27 StopSign.java // Displays a stop sign import java.awt.*; import jpb.*; public class StopSign { public static void main(String[] args) { // Create drawable frame DrawableFrame df = new DrawableFrame("Stop Sign"); df.show(); df.setSize(125, 125); // Obtain graphics context Graphics g = df.getGraphicsContext(); // Define coordinates of outer polygon (edge of sign) and // inner polygon (red portion) int[] xOuter = {36, 87, 123, 123, 87, 36, 0, 0}; int[] yOuter = {0, 0, 36, 87, 123, 123, 87, 36};

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 28 int[] xInner = {37, 86, 118, 118, 86, 37, 5, 5}; int[] yInner = {5, 5, 37, 86, 118, 118, 86, 37}; // Draw edge of sign in black g.setColor(Color.black); g.drawPolygon(xOuter, yOuter, xOuter.length); // Fill interior of sign with red g.setColor(Color.red); g.fillPolygon(xInner, yInner, xInner.length); // Display "STOP" in white g.setColor(Color.white); g.setFont(new Font("Helvetica", Font.BOLD, 36)); g.drawString("STOP", 13, 76); // Repaint frame df.repaint(); }

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 29 The FontMetrics Class There’s no simple relationship between the size of a font and the pixel sizes of the characters in the font. The FontMetrics class solves this problem by providing methods for computing the sizes of characters in a font.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 30 The FontMetrics Class 1.Create an object representing a particular font: Font f = new Font("SansSerif", Font.BOLD, 24); 2.The Font object is passed to the getFontMetrics method: FontMetrics fm = g.getFontMetrics(f); Or FontMetrics fm = df.getFontMetrics(f);

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 31 The FontMetrics Class The FontMetrics class provides methods that return information about the size of a font. Advance width—The distance from the beginning of a character to the place where the next character would go in a line of text:

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 32 The FontMetrics Class Ascent—The distance from the baseline to the top of most alphanumeric characters. Descent—The distance from the baseline to the bottom of most alphanumeric characters. Leading—The recommended amount of space between the descent of one line of text and the ascent of the next line. Height—The recommended distance between the baselines of adjacent lines of text. The height is the sum of the leading, ascent, and descent.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 33 The FontMetrics Class A figure that illustrates the meaning of ascent, descent, leading, and height:

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 34 The FontMetrics Class Commonly used FontMetrics methods: Description Action int getAscent() Returns the ascent for this font. int getDescent() Returns the descent for this font. int getHeight() Returns the height for this font. int getLeading() Returns the leading for this font. int getMaxAdvance() Returns the maximum advance width for any character in this font. int stringWidth(String str) Returns the advance width for str in this font.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 35 Program: Obtaining Font Information The FontInfo program displays information about a 20-point sans serif font. The information is displayed in the font itself:

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 36 FontInfo.java // Displays information about a font. Uses the FontMetrics // class to obtain the information to be displayed. import java.awt.*; import jpb.*; public class FontInfo { public static void main(String[] args) { // Create drawable frame DrawableFrame df = new DrawableFrame("Font Information"); df.show(); df.setSize(215, 175); // Get graphics context Graphics g = df.getGraphicsContext(); // Create font, get metrics for font, and compute height // of font Font f = new Font("SansSerif", Font.PLAIN, 20); FontMetrics fm = g.getFontMetrics(f); int height = fm.getHeight();

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 37 // Display information about font g.setFont(f); g.drawString("Ascent: " + fm.getAscent(), 10, height); g.drawString("Descent: " + fm.getDescent(), 10, height * 2); g.drawString("Height: " + height, 10, height * 3); g.drawString("Leading: " + fm.getLeading(), 10, height * 4); g.drawString("Maximum advance: " + fm.getMaxAdvance(), 10, height * 5); g.drawString("Width of \"Why?\": " + fm.stringWidth("Why?"), 10, height * 6); // Repaint frame df.repaint(); }

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Case Study: A Message Window The MessageWindow program will display a message within a frame. The user will enter a font (name and size), the number of lines in the message, and the message itself: Enter font name: Serif Enter font size: 40 Enter number of lines in message: 3 Enter line 1: I'm the Enter line 2: king of the Enter line 3: world! The program will allow spaces before and after each input item.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 39 Appearance of the Message Window A frame labeled “Message Window” will now appear, with the user’s message displayed in blue and each line centered within the frame:

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 40 Appearance of the Message Window The size of the frame will vary, depending on the message and the font: –The distance between the baselines of consecutive lines will match the font’s height. –The distance from the top of the graphics context to the baseline of the first line will be the font’s ascent plus its leading. –The space below the last line’s baseline will be equal to the font’s descent. –The amount of horizontal space on either side of the widest line will also match the font’s descent.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 41 Design of the MessageWindow Program Determining the size of the frame requires knowing the number of lines in the message and the width of the widest line (in pixels). The frame size also depends on the metrics of the font selected by the user. As a result, the MessageWindow program can’t display the message until all of it has been read.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 42 Design of the MessageWindow Program An outline of the MessageWindow program: 1. Prompt the user to enter the font name. 2. Prompt the user to enter the font size and convert the input to an integer. 3. Create the frame and font objects and obtain the metrics for the font. 4. Prompt the user to enter the number of lines in the message and convert the input to an integer. 5. Read and store the lines in the message, computing the width of the widest line. 6. Open the frame and set its size. 7. Obtain the graphics context; set the drawing color and the font. 8. Display the lines in the message. 9. Repaint the frame.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 43 Design of the MessageWindow Program The program will need to store the lines in the message until they can be displayed in step 8; an array is the logical choice. Step 5 can be written as a loop containing the following steps: 1. Prompt the user to enter a line; store the line in the array. 2. Compare the width of the line with the maximum width read so far, replacing the maximum width if necessary.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 44 MessageWindow.java // Program name: MessageWindow // Author: K. N. King // Written: // // Displays a message within a frame. Prompts the user to // enter a font name and size, the number of lines in the // message, and the message to be displayed. Spaces are // allowed before and after each input item. // // Once input is complete, a frame labeled "Message Window" // will appear. The message will be displayed in blue against // a white background, with the lines of the message centered // within the frame. The size of the frame will depend // on the message and the font. The distance between the // baselines of consecutive lines will match the font's // height. The distance from the top of the graphics context // to the baseline of the first line will be the font's ascent // plus its leading. The space below the last line's baseline // will be equal to the font's descent. The amount of // horizontal space on either side of the widest line will // also match the font's descent.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 45 import java.awt.*; import jpb.*; public class MessageWindow { public static void main(String[] args) { // Prompt user to enter font name SimpleIO.prompt("Enter font name: "); String fontName = SimpleIO.readLine().trim(); // Prompt user to enter font size; convert to integer form SimpleIO.prompt("Enter font size: "); String fontSizeString = SimpleIO.readLine().trim(); int fontSize = Integer.parseInt(fontSizeString); // Create drawable frame and font objects; // obtain font metrics DrawableFrame df = new DrawableFrame("Message Window"); Font f = new Font(fontName, Font.PLAIN, fontSize); FontMetrics fm = df.getFontMetrics(f);

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 46 // Prompt user to enter number of lines in message; // convert to integer form SimpleIO.prompt("Enter number of lines in message: "); String numLinesString = SimpleIO.readLine().trim(); int numLines = Integer.parseInt(numLinesString); // Read and store lines in message, computing width of // widest line String[] lines = new String[numLines]; int maxLineWidth = 0; for (int i = 0; i < numLines; i++) { // Prompt user to enter a line; store it in array SimpleIO.prompt("Enter line " + (i + 1) + ": "); lines[i] = SimpleIO.readLine().trim(); // Compare width of line with maximum width read so // far, replacing maximum width if necessary. int lineWidth = fm.stringWidth(lines[i]); if (lineWidth > maxLineWidth) maxLineWidth = lineWidth; }

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 47 // Open frame and set its size df.show(); int borderSize = fm.getDescent(); int height = fm.getHeight(); df.setSize(maxLineWidth + borderSize * 2, numLines * height + fm.getLeading()); // Obtain graphics context; set drawing color and font Graphics g = df.getGraphicsContext(); g.setColor(Color.blue); g.setFont(f); // Display lines in message int firstBaseline = fm.getLeading() + fm.getAscent(); for (int i = 0; i < numLines; i++) { int lineWidth = fm.stringWidth(lines[i]); g.drawString(lines[i], borderSize + (maxLineWidth - lineWidth) / 2, firstBaseline + i * height); } // Repaint frame df.repaint(); }

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 48 Remarks The second argument to drawString is borderSize + (maxLineWidth - lineWidth) / 2 Subtracting lineWidth from maxLineWidth and dividing by 2 yields the number of “extra” pixels on either side of line i. Adding this quantity to borderSize —the number of pixels on either side of the widest line—gives the x coordinate needed for line i to be centered within the frame.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Debugging A program that displays graphics in a frame can still display output using System.out.print and System.out.println. This output will appear in the window from which the program was launched. The ability to display messages in the original window is valuable for debugging.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 50 Printing Objects System.out.println, when given an object as its argument, will automatically call the object's toString method. ( System.out.print has the same ability.) All objects have a toString method. (If a class doesn’t declare a toString method, Java supplies one automatically through a mechanism known as inheritance.) Printing an object may supply useful debugging information about the object.

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 51 Printing Objects Printing a Color object: System.out.println(Color.lightGray); Output produced: java.awt.Color[r=192,g=192,b=192] Printing a Font object: Font f = new Font("SansSerif", Font.BOLD, 24); System.out.println(f); Output produced: java.awt.Font[family=SansSerif,name=SansSerif, style=bold,size=24]

Chapter 6: Graphics Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 52 Printing Objects Printing an object variable can be used to make sure that the variable actually contains an object and that the object has the expected state. It’s not necessary to test whether an object variable is null before printing it. If the variable’s value is null, the word null will be displayed. Although any object can be printed, the amount of information displayed varies from class to class.