850 likes | 1.05k Vues
http://www.codeproject.com/?cat=10 http://www.java2s.com/ http://www.javascriptfreecode.com/ http://www.javadb.com/ http://www.planet-source-code.com/vb/default.asp?lngWId=2 http://www.codemiles.com/java-codes/. Chapter 6. Graphics. 6.1 Creating a Drawing.
E N D
http://www.codeproject.com/?cat=10http://www.java2s.com/http://www.javascriptfreecode.com/http://www.javadb.com/http://www.planet-source-code.com/vb/default.asp?lngWId=2http://www.codemiles.com/java-codes/http://www.codeproject.com/?cat=10http://www.java2s.com/http://www.javascriptfreecode.com/http://www.javadb.com/http://www.planet-source-code.com/vb/default.asp?lngWId=2http://www.codemiles.com/java-codes/
Chapter 6 Graphics
6.1 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. • The Graphics class, which belongs to the java.awt package, makes it possible to create line drawings on the screen. • This class provides methods for drawing lines, rectangles, ovals, arcs, polygons, and polylines. • There’s also a method for displaying text.
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.
Graphics Contexts • An image consisting of black and white pixels:
Graphics Contexts • The pixels in a graphics context are arranged in rows and columns. • Each pixel can be identified by a pair of coordinates, with the x coordinate coming first. • The pixel at the upper left corner is located at position (0, 0). • A graphics context typically contains an image that’s being displayed on the user’s screen. • A graphics context can also be printed or used to store an image that's not visible on the screen.
Using Graphics Methods • If g is a graphics context, the pixels in g can be changed by calling one of the drawing methods in the Graphics class. • The drawLine method draws a line from one point to another: g.drawLine(x1, y1, x2, y2); (x1, y1) is one of the line’s endpoints; (x2, y2) is the other.
The DrawableFrame Class • The DrawableFrame class makes it easy to experiment with the Graphics class. • DrawableFrame belongs to the jpb package, which is not a part of the standard Java API. • A DrawableFrame object is a window in which images can easily be drawn. • When a DrawableFrame object is created, a title for the frame must be specified: DrawableFrame df = new DrawableFrame(title);
The DrawableFrame Class • Creating a DrawableFrame object doesn’t cause it to be displayed on the screen. • The show method is used to make a frame visible: df.show(); • The next step is to call setSize to specify the size of the frame’s graphics context: df.setSize(width, height); • The values in the call of setSize don’t determine the size of the frame itself, but rather the drawable area inside the frame.
The DrawableFrame Class • The appearance of a drawable frame in Windows:
The DrawableFrame Class • Before doing any drawing within a frame, it’s necessary to call getGraphicsContext: Graphics g = df.getGraphicsContext(); getGraphicsContext returns the frame’s graphics context. • After the pixels in g have been changed, the repaint method should be called to make sure that the changes appear on the screen: df.repaint();
Program: Drawing a Line • The DrawLine program illustrates how to create a DrawableFrame object and draw a line within it. • The line will go from (50, 50) to (100, 100).
DrawLine.java // Draws a line inside a frame 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(); } }
Drawing Rectangles • The Graphics class provides methods to draw three types of rectangles: • Ordinary rectangles • Rectangles with rounded corners • “Three-dimensional” rectangles • For each type, there’s one method to draw an outline and another to draw a filled rectangle. • Rectangle methods take four arguments or more: • The first two specify the rectangle’s upper left corner. • The next two specify the rectangle’s width and height.
Ordinary Rectangles • The drawRect method draws the outline of a rectangle: g.drawRect(x, y, width, height); • The fillRect method draws a filled rectangle: g.fillRect(x, y, width, height);
Ordinary Rectangles • An ordinary rectangle:
Rectangles with Rounded Corners • drawRoundRect draws an outline of a rectangle with rounded corners: g.drawRoundRect(x, y, width, height, arcWidth, arcHeight); • fillRoundRect draws a filled rectangle: g.fillRoundRect(x, y, width, height, arcWidth, arcHeight);
Rectangles with Rounded Corners • A rectangle with rounded corners:
Rectangles with Rounded Corners • The arcWidth argument specifies the horizontal diameter of the arc at each corner; arcHeight is the vertical diameter. • The upper-right corner of a rounded rectangle:
Drawing Ovals • The drawOval and fillOval methods will draw the outline of an oval or a filled oval, respectively: g.drawOval(x, y, width, height); g.fillOval(x, y, width, height); • x and y are the coordinates of the upper-left corner of an imaginary rectangle enclosing the oval. • width and height are the measurements of this rectangle.
Drawing Ovals • An oval: • If the width and height arguments are equal, drawOval and fillOval will draw circles.
Drawing Arcs • An arc is a segment of an oval. • The drawArc method requires six arguments: g.drawArc(x, y, width, height, startAngle, arcAngle); • The last two arguments specify the angle at which the oval starts and the “arc angle” of the oval. • Angles are measured in degrees, with zero degrees at 3 o’clock. • If the arc angle is positive, drawing is done in the counterclockwise direction. • If the arc angle is negative, drawing is done in the clockwise direction.
Drawing Arcs • If startAngle is 90 and arcAngle is 135, drawArc will draw the following shape:
Filling Arcs • The fillArc method draws a filled arc, which resembles a slice of pie. • The arguments to fillArc are the same as those for drawArc. • The filled area is a portion of the oval described by the first four arguments to fillArc. • The values of startAngle and arcAngle determine which portion is filled.
Filling Arcs • If startAngle is 90 and arcAngle is 135, fillArc will draw the following shape:
Drawing Polygons • A call of drawPolygon requires two arrays. • One array contains the x coordinates of the polygon’s vertices. The other array contains the y coordinates: int[] xCoordinates = {0, 100, 200}; int[] yCoordinates = {100, 0, 100}; • drawPolygon also requires a third argument, indicating the number of vertices: g.drawPolygon(xCoordinates, yCoordinates, xCoordinates.length);
Drawing Polygons • The result of calling drawPolygon:
Filling Polygons • Filling a polygon is similar to drawing one: g.fillPolygon(xCoordinates, yCoordinates, xCoordinates.length); • The third argument in the calls of drawPolygon and fillPolygon could have been 3. • Using xCoordinates.length or yCoordinates.length is a better choice. That way, the method call won’t have to be changed later if the number of vertices changes.
The Polygon Class • There’s a second technique for drawing (or filling) a polygon. • The java.awt package provides a class named Polygon. • Instances of this class represent specific polygons. • A statement that creates a Polygon object: Polygon p = new Polygon(xCoordinates, yCoordinates, xCoordinates.length);
The Polygon Class • The drawPolygon and fillPolygon methods will accept a Polygon object as their argument: g.drawPolygon(p); g.fillPolygon(p); • The Polygon class provides several useful operations on polygons. • The translate method changes the position of a polygon, and the addPoint method adds another vertex to a polygon.
Polygons in Java • A polygon in Java is any series of lines that form a closed region in two-dimensional space. • Some polygons are convex—a line drawn from any corner to any other corner will stay within the polygon:
Polygons in Java • Java doesn’t require that polygons be convex. • A legal polygon that’s not convex: • Java even allows the lines that form a polygon to cross.
Polygons in Java • The following polygon was created from four points (the four corners): • To produce this figure, the points were placed in the order {upper-left, lower-right, upper-right, lower-left}.
Drawing Polylines • A polyline is a series of lines, with each line after the first sharing an endpoint with the previous line. • A polyline is the same as a polygon, except that Java doesn’t automatically connect the last line back to the first to form a closed figure.
Drawing Polylines • Drawing a polyline is similar to drawing a polygon. • The first step is to create arrays containing the x and y coordinates of the points in the polyline: int[] xCoordinates = {0, 100, 200}; int[] yCoordinates = {100, 0, 100}; • The next step is to call drawPolyline: g.drawPolyline(xCoordinates, yCoordinates, xCoordinates.length); The arguments are the same as for drawPolygon.
Drawing Polylines • The result of calling drawPolyline:
6.2 Drawing in Color • The state of a Graphics object consists of more than just the pixels that it stores. • Each Graphics object also has a “current color.” All drawing is done in that color until the setColor method is called. • By default, the drawing color is black.
The Color Class • The argument to the setColor method must be an instance of the Color class, which belongs to the java.awt package. • A Color object can be created from three integers, indicating the red, green, and blue components of the color. • Each component has a value between 0 (no contribution) and 255 (maximum contribution). • The color “black” has red, green, and blue values of 0. “White” has values of 255 for all three.
Color Constants • The Java API provides constants representing frequently used colors. • These constants are defined inside the Color class itself.
Color Constants Red Green Blue Name Component Component Component black 0 0 0 blue 0 0 255 cyan 0 255 255 darkGray 64 64 64 gray 128 128 128 green 0 255 0 lightGray 192 192 192 magenta 255 0 255 orange 255 200 0 pink 255 175 175 red 255 0 0 white 255 255 255 yellow 255 255 0
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);
Calling the setColor Method • If no Color constant is available for a particular color, a new Color object can be created. • Code that sets the drawing color to light blue: Color lightBlue = new Color(64, 192, 255); g.setColor(lightBlue); • The new Color object can be passed directly to setColor, without storing it in a variable first: g.setColor(new Color(64, 192, 255));
6.3 Displaying Text • The drawString method is used to display text. • drawString requires three arguments: • A string containing the text to be displayed. • The x and y coordinates at which the text is to be displayed. • A call of drawString: g.drawString("Java rules!", x, y);
Coordinates for Displaying Text • x specifies the horizontal position of the first character in the string. y specifies the vertical position of the string’s baseline:
The Font Class • When text is written using drawString, the appearance of the text depends on the “current font,” which is stored in every Graphics object. • The current font can be changed by calling the setFont method: g.setFont(newFont); • The argument to setFont must be a Font object.
The Font Class • Font objects are created by calling the Font constructor, which requires three arguments: the font’s name, style, and size. • Font name. The font name is a string, such as "Monospaced", "Serif", or "SansSerif". • Other font names are allowed, but there’s no guarantee that a particular font will be available on the user’s computer.
The Font Class • 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.)
The Font Class • An example of using the Font constructor: Font f = new Font("SansSerif", Font.BOLD, 24); • The font name can be stored in a variable: Font f = new Font(fontName, Font.BOLD, 24); • Don’t put quotes around a variable name: Font f = new Font("fontName", Font.BOLD, 24); The Font constructor will treat "fontName" itself as the name of the desired font.