The Graphics class provides basic drawing methods, 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, mainly including: drawing line segments, drawing rectangles, drawing circles, drawing colored graphics, drawing ellipses, drawing arcs, drawing polygons, etc.
1. Draw a line <br />To draw a line 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 line segment between the point (3,3) and the point (50,50), and draws 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 <br />There are two types of rectangles: regular and rounded.
(1) There are two methods for drawing ordinary rectangles:
drawRect(int x, int y, int width, int height): Draw a rectangle surrounded by a wireframe. The parameters x and y specify the position of the upper left corner, and the parameters width and height are the width and height of the rectangle.
fillRect(int x, int y, int width, int height): fills a rectangle with a predetermined color to obtain a colored rectangular block.
The following code is an example of drawing a rectangle:
g.drawRect(80,100,40,25);//Draw the wire frame g.setColor(Color.yellow);g.fillRect(20,70,20,30);//Draw the coloring block
(2) There are two ways to draw a rounded rectangle:
drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight): It 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 height are the width and height of the rectangle; arcWidth and arcHeight are the transverse diameter and 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 a circle by drawing a rounded rectangle. When the width and height of the rectangle are equal, the transverse diameter of the rounded arc and the longitudinal diameter of the rounded arc are also equal, and equal to the width and height of the rectangle, a circle is drawn. See the comments in the above example. The former is to draw a circle, and the latter is to paint a circle block.
3. Draw a three-dimensional rectangle <br />There are two methods for drawing a three-dimensional rectangle:
draw3DRect(int x,int y,int width,int height, boolean raised): Draw a highlighted rectangle. Among them, 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, and the parameter raised is whether it is highlighted or not.
fill3DRect(int x,int y,int width,int height,boolean raised): Fill 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 coloring block
4. Draw an ellipse <br />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): draws an ellipse surrounded by lines. The parameters x and y specify the position of the upper left corner of the ellipse, and the parameters width and height are the horizontal and vertical axes.
fillOval(int x, int y, int width, int height): It is an oval filled with a predetermined color and is a coloring block. You can also use the method of drawing an ellipse to draw a circle. When the horizontal axis and the vertical axis are equal, the ellipse drawn is a circle.
The following code is an example of drawing an ellipse:
g.drawOval(10,10,60,120);//Draw an ellipse g.setColor(Color.cyan);g.fillOval(100,30,60,60);//Paint a circle g.setColor(Color.magenta) ;g.fillOval(15,140,100,50);//Paint the ellipse
5. Draw an arc
There are two ways to draw an arc:
drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): Draw an arc line as part of the ellipse. The center of the ellipse is the center of its enclosing rectangle, where the parameters are the coordinates (x, y) of the upper left corner of the enclosing rectangle, the width is width, and the height is height. The unit of parameter startAngle is "degree", and the starting angle of 0 degrees refers to the 3 o'clock position. The parameters startAngle and arcAngle indicate that starting from the startAngle angle, an arc of arcAngle degrees is drawn in the counterclockwise direction. By convention, positive degrees are in the counterclockwise direction. 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): Use the color set by the setColor() method to 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 an arc line g.drawArc(100,40,90,50,180,180);//Draw an arc line g.setColor(Color.yellow); g.fillArc(10,100,40,40,0,-270);//Fill the three-quarters of the ellipse missing the upper right corner g.setColor(Color.green); g.fillArc(60,110,110,60,-90,- 270);//Fill the three-quarters of the missing lower left corner of the ellipse
6. Draw polygons <br />A polygon is a closed planar figure formed by connecting multiple line segments end to end. The x-coordinates and y-coordinates of the endpoints of the polygon line segments are stored in two arrays respectively. To draw a polygon is to connect them with straight line segments in the order of the given coordinate points. The following are two commonly used 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 setColor() method. 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};//A polygon can be drawn only when the first and last points are the same 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 use polygon objects to draw polygons. Create a polygon object using the polygon class Polygon, and then use this object to draw polygons. Main methods of Polygon class:
For example, the following code draws a triangle and fills it with a yellow triangle. Note that using a polygon object to draw a closed polygon 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 polygon1=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 block <br />When you need to have an empty rectangle in the middle of a colored graphic, you can fill a rectangular block with the background color, which is equivalent to using an "eraser" on the rectangular block. The method is:
clearRect(int x, int y, int width, int height): Erase 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. Limit the drawing display area <br />Use a rectangle to represent the display area of the graph. The graph is required to be valid within the specified range. New coordinate values will not be recalculated, and the exceeded part will not be displayed automatically. The method is clipRect(int x, int y, int width, int height), which limits the display of graphics to the specified area, and does not display the excess part. When multiple restricted areas are covered, the intersection area of the restricted areas is obtained. For example, code:
g.clipRect(0,0,100,50);g.clipRect(50,25,100,50);
Equivalent to
g.clipRect(50,25,50,25);
9. Copy graphics <br />Use the method copyArea() of the Graphics class to copy graphics. The usage 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 graphics to the original position. Positive values mean offset to the right or down. Negative values are offsets to the left or up. The reference point for the displacement is the coordinate of the upper left corner of the rectangle to be copied.
For example, the following code illustrates the copying of graphics, by customizing part of one rectangle and the entirety 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] A small application rewrites the update() method to only clear the circle block, not the text, and the window displays a constantly 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); }}
A general drawing program must inherit JFrame and define a JFrame window subclass, and also inherit JPanel and define a JPanel subclass. Redefine the method paintComponent() in the JPanel subclass, and call the drawing method in this method to draw various graphics.
[Example] 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 the XOR drawing mode and the color is red g.setColor(Color.green); g.fillRect(20, 20, 80 , 40); //The actual color is a mixed color 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, the last half is green+yellow = gray g.setColor(Color.green); g.drawLine(80, 100, 180, 200); //The straight line is green+yellow = gray g.drawLine(100, 100, 200, 200); //Same as above/*Draw a partially overlapping straight line. The middle section of the original straight line is gray+gray=background color, and the extended part is green+yellow=gray.*/ g.drawLine(140, 140, 220, 220); g. setColor(Color.yellow); //Analyze the color changes of the following straight lines, which overlap with the previous force 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 demonstration"); setSize (300, 300); setVisible(true); }}