Home>

The graphics class provides basic drawing methods,The graphics2d class provides more powerful graphics capabilities.This section explains the graphics class, and the next section explains graphics2d.

The graphics class provides basic geometric drawing methods,Mainly:draw line segments, draw rectangles, draw circles, draw colored graphics, draw ovals, draw arcs, draw polygons, etc.

Line drawing

Draw a line 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 line segment between point (3,3) and point (50,50),Draw 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 types of rectangles:normal and rounded.

(1) There are two ways to draw ordinary rectangles:

drawrect (int x, int y, int width, int height):draw a rectangle surrounded by a wireframe.Where the parameters x and y specify the position of the upper left corner,The width and height parameters are the width and height of the rectangle.

fillrect (int x, int y, int width, int height):is to fill a rectangle with a predetermined color,Get a colored rectangular block.

The following code is an example of drawing a rectangle:

g.drawrect (80,100,40,25);//Draw the wireframe
 g.setcolor (color.yellow);g.fillrect (20,70,20,30);//Draw the color block

(2) There are two ways to draw rounded rectangles:

drawroundrect (int x, int y, int width, int height, int arcwidth, int archeight):is a rounded rectangle surrounded by lines.The parameters x and y specify the position of the upper left corner of the rectangle;The parameters width and heigth are the width and height of the rectangle;arcwidth and archeight are the transverse diameter of the fillet arc and the longitudinal diameter of the fillet arc, respectively.

fillroundrect (int x, int y, int width, int height, int arcwidth, int archeight):is 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);//paint 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 a circle

You can draw circles with rounded rectangles,When the width and height of the rectangle are equal,The transverse diameter of the fillet arc and the longitudinal diameter of the fillet arc are also equal.Equal to the width and height of the rectangle,The circle is drawn.See the comment in the example above,The previous one is drawing circles,The latter is painted round.

3. Draw a 3D Rectangle

There are two ways to draw a three-dimensional rectangle:

draw3drect (int x, int y, int width, int height, boolean raised):draw a highlighted rectangle.Where x and y specify the position of the upper left corner of the rectangle,The parameters width and height are the width and height of the rectangle.The parameter raised is highlighted 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 protruding rectangle:

g.draw3drect (80,100,40,25, true);//Draw a wireframe
 g.setcolor (color.yellow);g.fill3drect (20,70,20,30, true);//Draw a color block

4. Draw an oval

The ellipse is determined by the horizontal and vertical axes of the ellipse.There are two ways to draw an oval:

drawoval (int x, int y, int width, int height):is an oval shape drawn with a line.Where the parameters x and y specify the position of the upper left corner of the ellipse,The parameters width and height are the horizontal and vertical axes.

filloval (int x, int y, int width, int height):is an oval filled with a predetermined color,Is a colored block.You can also draw circles using the oval method.When the horizontal and vertical axes are equal,The oval drawn is a circle.

The following code is an example of drawing an oval:

g.drawoval (10,10,60,120);//Draw the ellipse
 g.setcolor (color.cyan);g.filloval (100,30,60,60);//painted round block
 g.setcolor (color.magenta);g.filloval (15,140,100,50);//painted ellipse

5. Draw an arcThere are two ways to draw an arc:

drawarc (int x, int y, int width, int height, int startangle, int arcangle):draw a circular arc of a part of the ellipse.The center of the ellipse is the center of its bounding rectangle,The parameters are the coordinates of the upper left corner of the bounding rectangle (x, y), the width is width, and the height is heigh. The unit of the startangle parameter is "degrees", and the starting angle of 0 degrees refers to the 3 o'clock position.The parameters startangle and arcangle indicate starting from the startangle angle,Draw arc of arcangle degrees counterclockwise. Conventionally, positive degrees are counterclockwise.Negative degrees are clockwise.For example, -90 degrees is 6 o'clock.

fillarc (int x, int y, int width, int height, int startangle, int arcangle):the color set with the setcolor () method,Draw a part of the colored ellipse.

The following code is an example of drawing an arc:

g.drawarc (10,40,90,50,0,180);//Draw arc line
 g.drawarc (100,40,90,50,180,180);//Draw circular arc
 g.setcolor (color.yellow);g.fillarc (10,100,40,40,0, -270);//fill three-quarters of the ellipse
 g.setcolor (color.green);g.fillarc (60,110,110,60, -90, -270);//Fill the three-quarter ellipse missing the bottom left corner

6. Draw Polygon

A polygon is a closed plan made up of multiple line segments connected end to end.The x and y coordinates of the endpoints of the polygon line segments are stored in two arrays, respectively.Drawing a polygon is to connect them with straight line segments in the order of given coordinate points.Here are two common methods for drawing polygons:

drawpolygon (int xpoints [], int ypoints [], int npoints):draw a polygon

fillpolygon (int xpoints [], int ypoints [], int npoints):color the polygon with the color set by the method setcolor ().The array xpoints [] stores x coordinate points, ypoints [] stores y coordinate points, and 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 first point.The following code implements filling a triangle and drawing an octagon.

int px1 []={50,90,10,50};//The first and last points are equal,To draw polygons
 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 using the polygon class polygon.Then use this object to draw a polygon.The main methods of the polygon class:

polygon ():create a polygon object,There are currently no coordinate points. polygon (int xpoints [], int ypoints [], int npoints):Creates a polygon object with the specified coordinate points. addpoint ():Add a coordinate point to the polygon object. drawpolygon (polygon p):draw a polygon. fillpolygon (polygon p):Fill the polygon with the specified color.

For example, the following code,Draw a triangle and fill a yellow triangle.Note that drawing closed polygons with polygon objects does not require that the first and last points 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 rectangle

When it is necessary to have a vacant rectangle in the middle of a coloring figure,This can be achieved by filling a rectangular block with the background color.Equivalent to using the "Eraser" on this rectangular block. The implementation method is:

clearrect (int x, int y, int width, int height):erases the coloring of a rectangular block specified by the parameters.

For example, the following code implements coloring that erases a rectangular block in a circle:

g.setcolor (color.blue);
 g.filloval (50,50,100,100);g.clearrect (70,70,40,55);

8. Limiting the display area for drawing

Use a rectangle to represent the display area of ​​the graphic,Requires graphics to be valid within a specified range,Do not recalculate new coordinate values,The automatically implemented excess is not displayed.The method is cliprect (int x, int y, int width, int height), which limits the display of graphics in the specified area.The excess is not displayed.When multiple restricted areas are covered,Obtain the intersection area of ​​the restricted area.For example, the code:

g.cliprect (0,0,100,50);g.cliprect (50,25,100,50);

Equivalent to

g.cliprect (50,25,50,25);

9. Copy graphics

Copy graphics using the graphics class method copyarea (),Its format is:

copyarea (int x, int y, int width, int height, int dx, int dy), dx and dy respectively represent the number of pixels offset by pasting the graphic to the original positionPositive values ​​are offset to the right or down,Negative values ​​are offset to the left or up.The reference point of the displacement is the upper-left corner coordinate of the rectangle to be copied.

For example, the following code is a schematic copy,Make a part of one rectangle and the whole of another rectangle.

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);

[Example] The applet rewrites the update () method to clear only the round blocks.Does not clear text,The window shows a moving red square.

import java.applet. *;import java.awt. *;public 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'm learning the update () method", 100,100); try {  thread.sleep (100); } catch (interruptedexception e) {} repaint (); } public void update (graphics g) { g.clearrect (i, 10,200,100);//Do not clear "I am learning the update () method" paint (g); }}

General drawing programs should inherit jframe, define a jframe window subclass,Also inherit jpanel and define a jpanel subclass. Redefine the method paintcomponent () in the jpanel subclass, call the drawing method in this method,Draw various graphics.

[Example] An application using xor drawing mode.

import javax.swing. *;
import java.awt. *;
public class example7_4 extends jframe {
 public static void main (string args []) {
 graphicsdemo mygraphicsframe=new graphicsdemo ();
 }
}
class shapespanel extends jpanel {
 sharpespanel () {
 setbackground (color.white);
 }
 public void paintcomponent (graphics g) {
 super.paintcomponent (g);
 setbackground (color.yellow);//The background color is yellow
 g.setxormode (color.red);//Set xor drawing mode,Color is red
 g.setcolor (color.green);
 g.fillrect (20, 20, 80, 40);//The actual color is a mixture of green + yellow=gray
 g.setcolor (color.yellow);
 g.fillrect (60, 20, 80, 40);//The second 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 green + yellow mixed color=gray.
 g.fillrect (60, 70, 80, 40);
 //The first half is (green + yellow) + gray=background color, and the second 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);//same as above
 /* Draw some overlapping lines again.
The middle part of the original straight line is gray + gray=background color, and the extension is green + yellow=gray. * /
 g.drawline (140, 140, 220, 220);
 g.setcolor (color.yellow);//Analyze the following line color changes,Overlaps with earlier 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 ("Demonstration of basic drawing methods");
 setsize (300, 300);
 setvisible (true);
 }
}
  • Previous Using Fragment in Android
  • Next C # operation JSON method summary