A detailed description of how to draw using the Java Graphics class

Source: Internet
Author: User
Tags mixed

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);//Paint shading 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 round 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

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 circular arc g.drawarc (100,40,90,50,180,180);//Draw round arc g.setcolor (color.yellow); G.fillarc (10,100,40,40,0,-270);//fill in the top 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 end 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 ();p olygon1.addpoint (50,10);p olygon1.addpoint (90,50);p olygon1.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);


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" applet overrides the Update () method, clears only the circle block, does not clear the text, and the window displays a constantly moving red square.

Import Java.applet.*;import java.awt.*;p ublic class Example7_3 extends applet{int i=1; public void init () {SetBackground ( Color.yellow); public void Paint (Graphics g) {i = i+8; if (i>160) I=1; G.setcolor (color.red); G.fillrect (i,10,20,20); g.DrawString (" I am learning Update () method ", 100,100); try{  Thread.Sleep (+),} catch (Interruptedexception e) {} repaint (),} public void Update (Graphics g) {G.clearrect (i , 10,200,100);//Do not clear "I am learning Update () method" Paint (g); }}


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" an application that uses XOR drawing mode.

Import Javax.swing.*;import java.awt.*;p ublic class Example7_4 extends jframe{public static void Main (String args[]) {Gra Phicsdemo mygraphicsframe = new Graphicsdemo (); }}class Shapespanel extends jpanel{sharpespanel () {setbackground (color.white);} public void Paintcomponent (Graphics g) {super.paintcomponent (g); SetBackground (color.yellow);//Background color is yellow g.setxormode (color.red);//Set XOR drawing mode, color red G.setcolor (Color.green); G.fillrect (20, 20, 80, 40); The actual color is the mixed color of green + yellow = 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. G.fillrect (60, 70, 80, 40); 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); Ditto/* Redraw partially overlapping lines. The middle segment of the original line is Gray + Gray = background color, the extension part is green+yellow=gray.*/g.drawline (140, 140, 220, 220); G.setcolor (Color.yellow); Analyze the following line color changes, overlapping with previous forces G.drawliNE (20, 30, 160, 30); G.drawline (20, 75, 160, 75); }}class Graphicsdemod extends jframe{public Graphicsdemo () {This.getcontentpane (). Add (New Shapespanel ()); SetTile (" Basic Drawing Method Demo "); SetSize (300, 300); SetVisible (TRUE); }}


A detailed description of how to draw using the Java Graphics class

Related Article

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.