Kĩ thuật lập trình - Graphics and java 2d™

An ArrayIndexOutOfBoundsException is thrown if the number of points specified in the third argument to method drawPolygon or method fillPolygon is greater than the number of elements in the arrays of coordinates that specify the polygon to display.

ppt74 trang | Chia sẻ: huyhoang44 | Lượt xem: 679 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Graphics and java 2d™, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
12Graphics and Java 2D™ 1 One picture is worth ten thousand words. Chinese proverbTreat nature in terms of the cylinder, the sphere, the cone, all in perspective.Paul CézanneColors, like features, follow the changes of the emotions.Pablo PicassoNothing ever becomes real till it is experienced—even a proverb is no proverb to you till your life has illustrated it.John Keats2OBJECTIVESIn this chapter you will learn:To understand graphics contexts and graphics objects.To manipulate colors.To manipulate fonts.To use methods of class Graphics to draw lines, rectangles, rectangles with rounded corners, three-dimensional rectangles, ovals, arcs and polygons.To use methods of class Graphics2D from the Java 2D API to draw lines, rectangles, rectangles with rounded corners, ellipses, arcs and general paths.To specify Paint and Stroke characteristics of shapes displayed with Graphics2D.312.1   Introduction 12.2   Graphics Contexts and Graphics Objects12.3   Color Control 12.4   Font Control 12.5   Drawing Lines, Rectangles and Ovals 12.6   Drawing Arcs 12.7   Drawing Polygons and Polylines 12.8   Java 2D API 12.9   Wrap-Up 412.1  IntroductionJava contains support for graphics that enable programmers to visually enhance applicationsJava contains many more sophisticated drawing capabilities as part of the Java 2D API ClassesColor Font, FontMetricsGraphics2D Polygon BasicStroke GradientPaint, TexturePaint Java 2D shape classes5Fig. 12.1 | Classes and interfaces used in this chapter from Java’s original graphics capabilities and from the Java 2D API. [Note: Class Object appears here because it is the superclass of the Java class hierarchy.]612.1  IntroductionJava coordinate systemUpper-left corner of a GUI component has the coordinates (0, 0)Contains x-coordinate (horizontal coordinate) - horizontal distance moving right from the left of the screen Contains y-coordinate (vertical coordinate) - vertical distance moving down from the top of the screenCoordinate units are measured in pixels. A pixel is a display monitor’s smallest unit of resolution.7Fig. 12.2 | Java coordinate system. Units are measured in pixels. 8Portability Tip 12.1Different display monitors have different resolutions (i.e., the density of the pixels varies). This can cause graphics to appear to be different sizes on different monitors or on the same monitor with different settings. 912.2  Graphics Contexts and Graphics ObjectsA Java graphics context enables drawing on the screenClass Graphics Manages a graphics context and draws pixels on the screenAn abstract class – contributes to Java’s portabilityMethod paintComponentUsed to draw graphicsMember of class JComponent, subclass of ComponentGraphics object passed to paintComponent by the system when a lightweight Swing component needs to be repainted If programmer needs to have paintComponent execute, a call is made to method repaint1012.3  Color ControlClass Color declares methods and constants for manipulating colors in a Java programEvery color is created from a red, a green and a blue component – RGB values11Fig. 12.3 | Color constants and their RGB values. 12Fig. 12.4 | Color methods and color-related Graphics methods. 13Method paintComponent paints JPanelSet current drawing color with method setColorDraw filled rectangle using current colorDraw text value of current colorSet current drawing color, specify float arguments to Color constructorSet current drawing color using Color constant14Retrieving RGB values using methods getRed, getGreen and getBlue1516Look-and-Feel Observation 12.1Everyone perceives colors differently. Choose your colors carefully to ensure that your application is readable. Try to avoid using many different colors in close proximity. 17To change the color, you must create a new Color object (or use one of the predeclared Color constants). Like String objects, Color objects are immutable (not modifiable). Software Engineering Observation 12.11812.3  Color ControlJColorChooser GUI component enables application users to select colors Method showDialog creates a JColorChooser object, attaches it to a dialog box and displays the dialog Modal dialogAllows the user to select a color from a variety of color swatches Tabs – Swatches, HSB and RGB19Import JColorChooser class20Display JColorChooser dialogReference to parent componentTitle bar textInitial selected colorChange background color of JPanel2122Select a color from one of the color swatches.23Fig. 12.9 | HSB and RGB tabs of the JColorChooser dialog.Sliders to select the red, green and blue color components2412.4  Font ControlClass FontConstructor takes three arguments—the font name, font style and font sizeFont name – any font currently supported by the system on which the program is runningFont style –Font.PLAIN, Font.ITALIC or Font.BOLD. Font styles can be used in combination Font sizes – measured in points. A point is 1/72 of an inch.Methods getName, getStyle and getSize retrieve information about Font objectGraphics methods getFont and setFont retrieve and set the current font, respectively25Fig. 12.10 | Font-related methods and constants. (Part 1 of 2)26Fig. 12.10 | Font-related methods and constants. (Part 2 of 2)27Portability Tip 12.2The number of fonts varies greatly across systems. Java provides five logical font names—Serif, Monospaced, SansSerif, Dialog and DialogInput—that can be used on all Java platforms. The Java runtime environment (JRE) on each platform maps these logical font names to actual fonts installed on the platform. The actual fonts used may vary by platform.28Creating and setting Font objectsFont nameFont styleFont size29Combining stylesRetrieve font name and size of Graphics object’s current Font3031Software Engineering Observation 12.2 To change the font, you must create a new Font object. Font objects are immutable—class Font has no set methods to change the characteristics of the current font. 32Font MetricsFont class methodsgetFamily – returns name of font family to which the current font belongs isPlain, isBold, isItalic – used to determine font styleFont metrics – precise information about a fontHeightDescent – amount a character dips below the baselineAscent – amount a character rises above the baselineLeading – the interline spacingClass FontMetrics declares several methods for obtaining font metrics 33Fig. 12.13 | Font metrics.34Fig. 12.14 | FontMetrics and Graphics methods for obtaining font metrics. 35Retrieve FontMetrics object of current FontRetrieve font metric values36373812.5  Drawing Lines, Rectangles and OvalsGraphics methods for drawing lines, rectangles and ovals fillRoundRect and drawRoundRect – draw rectangles with rounded cornersbounding rectangle—the area in which a rounded rectangle or oval will be drawndraw3DRect and fill3DRect – draw a 3D rectangle that is either raised or lowereddrawOval and fillOval – draw ovals39Fig. 12.17 | Graphics methods that draw lines, rectangles and ovals. (Part 1 of 2)40Fig. 12.17 | Graphics methods that draw lines, rectangles and ovals. (Part 2 of 2)41Draw a straight lineDraw an empty rectangleDraw a filled rectangle42Draw a filled rectangle with rounded cornersDraw an empty rectangle with rounded cornersDraw an empty rectangle that is raisedDraw a filled rectangle that is loweredDraw an empty ovalDraw a filled oval4344fillRoundRectdrawRoundRectdrawOvalfillOvaldrawLinedrawRectfillRectdraw3DRectfill3DRect45Fig. 12.20 | Arc width and arc height for rounded rectangles.46Fig. 12.21 | Oval bounded by a rectangle.4712.6  Drawing ArcsAn arc is drawn as a portion of an ovalArcs sweep (i.e., move along a curve) from a starting angle by the number of degrees specified by their arc angleCounterclockwise sweep measured in positive degreesClockwise sweep measured in negative degreesGraphics methods drawArc and fillArc are used to draw arcs48Fig. 12.22 | Positive and negative arc angles.49Fig. 12.23 | Graphics methods for drawing arcs. 50x- and y-coordinates for upper left corner of bounding rectangleWidth and height of bounding rectangleStarting angleSweep angleDraw empty arcs51Draw filled arcsNegative values indicate arc should sweep clockwise52535412.7  Drawing Polygons and PolylinesPolygonsClosed multisided shapes composed of straight line segmentsGraphics methods drawPolygon and fillPolygon to display polygonsPolygons can be represented using class Polygon – class contains method addPoint to add points to a Polygon PolylinesSequences of connected pointsGraphics method drawPolyline to display polylines55Fig. 12.26 | Graphics methods for polygons and class Polygon methods. (Part 1 of 2)56Fig. 12.26 | Graphics methods for polygons and class Polygon methods. (Part 2 of 2)57Create Polygon object from sets of x- and y-coordinatesDraw an empty PolygonDraw polyline from sets of x- and y-coordinates58Draw polygon from sets of x- and y-coordinates, without creating Polygon objectAdd coordinates to Polygon with method addPoint5960Result of line 28Result of line 37Result of line 23Result of line 1861An ArrayIndexOutOfBoundsException is thrown if the number of points specified in the third argument to method drawPolygon or method fillPolygon is greater than the number of elements in the arrays of coordinates that specify the polygon to display. Common Programming Error 12.16212.8  Java 2D APIProvides advanced two-dimensional graphics capabilities for detailed and complex graphical manipulationsFeatures for processing line art, text and imagesAccomplished with Graphics2D class63Lines, Rectangles, Round Rectangles, Arcs and EllipsesJava 2D shapes specified with double-precision floating-point values – Line2D.Double, Rectangle2D.Double, RoundRectangle2D.Double, Arc2D.Double, Ellipse2D.DoublePainting with Graphics2D objectMethod setPaint – sets color for Graphics2D object when shapes are drawn as Paint objectPaint object can be a predeclared Color object, or an instance of GradientPaint, SystemColor or TexturePaint classesGradientPaint used for drawing with a gradient – gradients can be cyclic or acyclicTexturePaint used for painting by replicating a stored image64Lines, Rectangles, Round Rectangles, Arcs and EllipsesGraphics2D method fill used to draw a filled Shape object – an object that implements interface ShapeGraphics2D method draw used to draw a Shape objectSetting stroke of a line or borderGraphics2D method setStroke – requires argument that implements interface Stroke BasicStroke class – can specify width of line, end caps, line joinsArc2D.Double constantsArc2D.PIE – arc should be closed by two lines—one from starting point to center, one from center to ending pointArc2D.CHORD – draws a line from the starting point to the ending pointArc2D.OPEN – arc should not be closed65Java 2D API shape classesCreating a Graphics2D reference66Set Graphics2D object to draw using a gradient from blue to yellowDraw ellipse filled using gradientSet width of border to 10 pixelsCreate image to be used for TexturePaint object67Create TexturePaint object from imageDraw rounded rectangle, filled with repeating imageDraw arc using white border, 6 pixels wideDraw solid green lineSet stroke to use dashesDraw dashed yellow line6869General PathsA general path is a shape constructed from straight lines and complex curvesClass GeneralPathMethod moveTo specifies the first point in a general pathMethod lineTo draws a line to the next point in the pathMethod closePath completes the general pathGraphics2D method translate – used to move the drawing originGraphics2D method rotate – used to rotate the next displayed shape70Set starting point of GeneralPath objectCreate GeneralPath object71Add lines of general pathDraw line from last point to first pointRotate approximately 18 degreesDraw star at current angle around origin727374

Các file đính kèm theo tài liệu này:

  • pptjavahtp7e_12_9109_8818.ppt