How much Java knows (98) the drawing method of the Graphics class

Source: Internet
Author: User

The Graphics class provides a basic drawing method, and the Graphics2D class provides more powerful drawing capabilities. This section explains the graphics class, and the next section explains Graphics2D.

The Graphics class provides basic geometric drawing methods, such as: Draw line segments, draw rectangles, draw circles, draw colored graphics, draw ellipses, draw arcs, draw polygons, and so on.

1. Draw the line
To draw a segment in the window, you can use the DrawLine () method of the Graphics class:
DrawLine (int x1,int y1,int x2,int y2)
For example, the following code draws a segment between a point (3,3) and a point (50,50), drawing a point at the point (100,100).
G.drawline (3,3,50,50);//Draw a line segment
G.drawline (100,100,100,100);//Draw a point.

2. Draw a rectangle
There are two kinds of rectangles: normal and rounded.
(1) There are two ways to draw a normal rectangle:

    • DrawRect (int x,int y,int width,int height): A rectangle that draws a wireframe surround. Where the parameters x and y Specify the position of the upper-left corner, the width and height of the parameter are the width and height of the rectangle.
    • FillRect (int x,int y,int width,int height): Fills a rectangle with a predetermined color, resulting in a shaded rectangular block.

The following code is an example of drawing a rectangle:
G.drawrect (80,100,40,25);//Draw wireframe
G.setcolor (Color.yellow); G.fillrect (20,70,20,30);//Painting coloring blocks

(2) There are two ways to draw a rounded rectangle:

    • Drawroundrect (int x,int y,int width, int height, int arcwidth, int archeight): is a rounded rectangle surrounded by lines. Where the parameters x and y Specify the position of the upper-left corner of the rectangle, the width and heigth of the parameters are the width and height of the rectangle, and the Arcwidth and archeight are the transverse diameters of the fillet arcs and the longitudinal diameters of the fillet arcs.
    • Fillroundrect (int x,int y,int width,int height,int arcwidth,int archeight): A rounded rectangle filled with a predetermined color. The meaning of each parameter is the same as the previous method.

The following code is an example of drawing a rectangle:
G.drawroundrect (10,10,150,70,40,25);//Draw a rounded rectangle
G.setcolor (Color.Blue); G.fillroundrect (80,100,100,100,60,40);//apply a rounded rectangular block
G.drawroundrect (10,150,40,40,40,40);//Draw a circle
G.setcolor (color.red); G.fillroundrect (80,100,100,100,100,100);//Draw round pieces
Circular Rectangle method can be used to draw a circle, when the width and height of the rectangle is equal, the transverse diameter of the fillet arc and the longitudinal diameter of the fillet arc is also equal, and equal to the width and height of the rectangle, the picture is a circle. See the note in the above example, the previous one is a circle, the latter one is a piece of paint.

3. Draw three-dimensional rectangles
There are two ways to draw a three-dimensional rectangle:

    • Draw3drect (int x,int y,int width,int height, Boolean raised): Draws a highlighted rectangle. where x and y specify the position of the upper-left corner of the rectangle, the parameter width and height are the width and height of the rectangle, and the parameter raised is prominent or not.
    • Fill3drect (int x,int y,int width,int Height,boolean raised): Fills a highlighted rectangle with a predetermined color.

The following code is an example of drawing a highlighted rectangle:
G.draw3drect (80,100,40,25,true);//Draw a wireframe
G.setcolor (Color.yellow); G.fill3drect (20,70,20,30,true);//Draw a coloring block

4. Draw an oval
Ellipses are determined by the horizontal and vertical axes of the ellipse. There are two ways to draw an ellipse:

    • DrawOval (int x,int y,int width,int height): It is the ellipse that draws the line around. where parameter x and parameter y specify the position of the upper-left corner of the ellipse, the width and height of the parameter are the horizontal and vertical axes.
    • Filloval (int x,int y,int width,int height): An ellipse filled with a predetermined color, is a shaded block. You can also draw a circle with the oval method, and when the horizontal and vertical axes are equal, the ellipse that is drawn is rounded.

The following code is an example of drawing an ellipse:
G.drawoval (10,10,60,120);//Draw Ellipse
G.setcolor (Color.cyan); G.filloval (100,30,60,60);//Tu Yuan
G.setcolor (Color.magenta); G.filloval (15,140,100,50);//Tu ellipse

5. Draw Arcs
There are two ways to draw an arc:

    • DrawArc (int x,int y,int width,int height,int startangle, int arcangle): Draws the arc line part of the ellipse. The center of the ellipse is the center of its bounding rectangle, where the parameter is the upper-left coordinate of the bounding rectangle (x, y), width is width, and height is heigh. The units of the parameter startangle are "degrees", The starting angle of 0 degrees refers to the 3 o'clock azimuth. The parameters startangle and Arcangle represent the arc of the Arcangle degree from the startangle angle, the contract, the positive degree is counterclockwise, the negative degree is clockwise, for example-90 degrees is the 6 o'clock position.
    • Fillarc (int x,int y,int width, int height, int startangle, int arcangle): A color set with the SetColor () method to draw part of the shaded ellipse.

The following code is an example of drawing arcs:
G.drawarc (10,40,90,50,0,180);//Draw round arcs
G.drawarc (100,40,90,50,180,180);//Draw round arcs
G.setcolor (Color.yellow); G.fillarc (10,100,40,40,0,-270);//fill in the upper right corner of the three-fourths ellipse
G.setcolor (Color.green); G.fillarc (60,110,110,60,-90,-270);//Fill three-fourths ellipse with missing left corner

6. Draw Polygons
A polygon is a closed plan that is connected with the end of a line of multiple lines. The x-coordinate and y-coordinate of the end of the polygon segment are stored in two arrays, and the drawing polygon is connected by a straight segment in the order of the given coordinate points. Here are two common ways to draw a polygon:

    • DrawPolygon (int xpoints[],int ypoints[],int npoints): Draw a polygon
    • FillPolygon (int xpoints[],int ypoints[],int npoints): Color-shaded polygons set with Method SetColor (). where array xpoints[] stores x-coordinate points, ypoints[] stores y-coordinate points, npoints is the number of coordinate points.


Note that the above method does not automatically close the polygon, to draw a closed polygon, the last point of the given coordinate point must be the same as the 1th. The following code implements populating a triangle and drawing a eight-sided shape.
int px1[]={50,90,10,50};//The first and last point of the phase weight to draw the polygon
int py1[]={10,50,50,10};
int px2[]={140,180,170,180,140,100,110,140};
int py2[]={5,25,35,45,65,35,25,5};
G.setcolor (Color.Blue);
G.fillpolygon (px1,py1,4);
G.setcolor (color.red);
G.drawpolygon (px2,py2,9);

You can also draw polygons with polygon objects. Create a Polygon object with the Polygon class polygon, and then draw the polygon with this object. The main methods of the Polygon class are:

    • Polygon (): Creates a Polygon object with no coordinate points at the moment.
    • Polygon (int xpoints[],int ypoints[],int npoints): Creates a Polygon object with the specified coordinate point.
    • Addpoint (): Adds a coordinate point to the Polygon object.
    • DrawPolygon (Polygon P): Draws a polygon.
    • FillPolygon (Polygon P): Fills the polygon with the specified color.


For example, the following code draws a triangle and fills a yellow triangle. Note that drawing closed polygons with polygon objects does not require the first end point to coincide.
int x[]={140,180,170,180,140,100,110,100};
int y[]={5,25,35,45,65,45,35,25};
Polygon ponlygon1=new Polygon ();
Polygon1.addpoint (50,10);
Polygon1.addpoint (90,50);
Polygon1.addpoint (10,50);
G.drawpolygon (Polygon1);
G.setcolor (Color.yellow);
Polygon polygon2 = new Polygon (x,y,8);
G.fillpolygon (Polygon2);

7. Erase Rectangular Blocks
When there is an empty rectangle in the middle of a shaded graphic, a rectangular block can be filled with the background color, which is equivalent to using "eraser" on the rectangle block. The way to do this is:
Clearrect (int x,int y, int width,int height): Erases the shading of a rectangular block specified by a parameter.
For example, the following code implements the shading of a rectangular block in a circle:
G.setcolor (Color.Blue);
G.filloval (50,50,100,100); G.clearrect (70,70,40,55);

8. Limit the area of the drawing display
Use a rectangle to represent the display area of the graphic, requiring the graphic to be valid within the specified range, without recalculating the new coordinate value, and automatically implementing the Out-of-section display. The method is cliprect (int x,int y,int width,int height), which restricts the display of the graphic within the specified area, and does not appear outside the section. When multiple restricted areas have coverage, the intersection area of the restricted area is obtained. For example, code:
G.cliprect (0,0,100,50); G.cliprect (50,25,100,50);
Equivalent
G.cliprect (50,25,50,25);

9. Copying Graphics
Using the Graphics class method, Copyarea () can be used to copy graphics, using the following format:
Copyarea (int x,int y,int width,int height, int dx, int dy), dx and dy respectively represent the number of pixels that are pasted into the original position, positive values are shifted to the right or downward, and negative values are left or upward offset. The reference point of the displacement is the coordinate of the upper-left corner of the rectangle to copy.

For example, the following code-shaped copy, which is a part of one rectangle, and all of the other rectangles are made separately.
G.drawrect (10,10,60,90);
G.fillrect (90,10,60,90);
G.copyarea (40,50,60,70,-20,80);
G.copyarea (110,50,60,60,10,80);

The "Example 12-3" applet overrides the Update () method, clears only the circle block, does not clear the text, and the window displays a constantly moving red square.

1 Importjava.applet.*;2 Importjava.awt.*;3  Public classExample7_3extendsapplet{4     intI=1;5      Public voidinit () {6 SetBackground (color.yellow);7     }8      Public voidPaint (Graphics g) {9i = i+8;if(i>160) I=1;TenG.setcolor (color.red); G.fillrect (i,10,20,20); Oneg.DrawString ("I'm Learning Update () method", 100,100); A         Try{ -Thread.Sleep (100); -         } the         Catch(Interruptedexception e) {} - repaint (); -     } -      Public voidUpdate (Graphics g) { +G.clearrect (i,10,200,100);//do not clear "I am learning Update () method" - Paint (g); +     } A}



The general drawing program inherits JFrame, defines a jframe window subclass, inherits JPanel, and defines a jpanel subclass. Redefine the method Paintcomponent () in the JPanel subclass, call the drawing method in this method, draw various graphs.

Example 12-4 uses an XOR drawing mode application.

1 Importjavax.swing.*;2 Importjava.awt.*;3  Public classExample7_4extendsjframe{4      Public Static voidMain (String args[]) {5Graphicsdemo Mygraphicsframe =NewGraphicsdemo ();6     }7 }8 classShapespanelextendsjpanel{9 Sharpespanel () {Ten SetBackground (color.white); One     } A      Public voidpaintcomponent (Graphics g) { -         Super. paintcomponent (g); -SetBackground (Color.yellow);//background color is yellow theG.setxormode (color.red);//set XOR drawing mode, color is red - G.setcolor (color.green); -G.fillrect (20, 20, 80, 40);//The actual color is green + Yellow's mixed color = Gray - G.setcolor (color.yellow); +G.fillrect (60, 20, 80, 40);//The latter half is Yellow+yellow=read, the first half is yellow+ gray - G.setcolor (color.green); +G.fillrect (20, 70, 80, 40);//The actual color is the mixed color of Green+yellow = Gray. AG.fillrect (60, 70, 80, 40); at         //The first half is (green+yellow) +gray = background color, and the latter half is Green+yellow = Gray - G.setcolor (color.green); -G.drawline (80, 100, 180, 200);//the line is Green+yellow = Gray -G.drawline (100, 100, 200, 200);//Ibid . -         /*draw partially overlapping lines. The middle segment of the original line is Gray + Gray = background color, and the extended part is Green+yellow=gray.*/ -G.drawline (140, 140, 220, 220); inG.setcolor (Color.yellow);//analyze the following line color changes, overlapping with previous forces -G.drawline (20, 30, 160, 30); toG.drawline (20, 75, 160, 75); +     } - } the classGraphicsdemodextendsjframe{ *      PublicGraphicsdemo () { $          This. Getcontentpane (). Add (NewShapespanel ());Panax NotoginsengSetTile ("Basic Drawing Method Demo"); -SetSize (300, 300); theSetVisible (true); +     } A}

Series Articles:

Java know how much (top)Java know how much (medium)Java knows how many () Java vectors (vector) and their applicationsJava know how much (79) hash table and its applicationJava know how much (80) graphical Interface design basicsJava know how much (81) frame window BasicsJava know how much (82) Introduction to tags, buttons, and button eventsJava know how much (83) Panel Basics: JPanel and JScrollPaneJava know how much (84) layout design of graphical interfaceJava know how much (85) text box and text areaJava know how much (86) input and output of text box and text areaJava know how much (87) Select boxes and radio buttonsJava know how many (88) lists and combo boxesJava know how many (89) lists and combo boxesJava know how much (90) menuJava know how much (91) dialog boxJava know how much (92) scroll barJava know how much (93) mouse EventsJava know how much (94) keyboard EventsJava know how much (95) Drawing BasicsJava know how much (96) set the font and color of the drawingJava know how much (97) Drawing Mode Overview

How much Java knows (98) the drawing method of the Graphics class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.