Method for drawing using Java's Graphics class

  • 2020-04-01 04:15:15
  • OfStack

The Graphics class provides basic drawing methods, and the Graphics2D class provides more powerful drawing capabilities. This section is on the Graphics class, and the next section is on Graphics2D.

Graphics class provides the basic drawing methods of geometric Graphics, mainly including: draw line segments, draw rectangles, draw circles, draw colored Graphics, draw ellipses, draw arcs, draw polygons, etc.

1. Draw lines
Draw a line segment in the window, using 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 points (3,3) and points (50,50), and a point at points (100,100).


  g.drawLine(3,3,50,50);//Let me draw a line segment
  g.drawLine(100,100,100,100);// Let me draw a dot. 

2. Draw a rectangle
There are two types of rectangles: regular and rounded.
(1) there are two ways to draw a normal rectangle:
DrawRect (int x,int y,int width,int height) : draws a rectangle around a wire frame. Where the parameters x and y specify 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 get a colored rectangle block.
The following code is an example of drawing a rectangle:


 g.drawRect(80,100,40,25);//The painting line
 g.setColor(Color.yellow);g.fillRect(20,70,20,30);// Painted with color piece 

(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 top left corner of the rectangle; The parameters width and heigth are the width and height of the rectangle. ArcWidth and arcHeight are respectively the transverse diameter and the longitudinal diameter of the rounded corner arc.
FillRoundRect (int x,int y,int width,int height,int arcWidth,int archeight) : is a rounded rectangle filled with a predetermined color. Each parameter has the same meaning as the previous method.
The following code is an example of drawing a rectangle:


 g.drawRoundRect(10,10,150,70,40,25);//Draw a rectangle with rounded corners
 g.setColor(Color.blue); g.fillRoundRect(80,100,100,100,60,40);//Paint a rounded rectangle block
 g.drawRoundRect(10,150,40,40,40,40);//A circle
 g.setColor(Color.red); g.fillRoundRect(80,100,100,100,100,100);//A circle block 


You can draw a circle by drawing a rectangle with rounded corners. When the width and height of the rectangle are the same, the transverse diameter of the arc with rounded corners is the same as the longitudinal diameter of the arc with rounded corners, and is equal to the width and height of the rectangle, you draw a circle. See the comments in the example above, where the first is to draw a circle and the second is to paint a circle block.

3. Draw a three-dimensional rectangle
There are two ways to draw a 3d 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 top left corner of the rectangle, the parameters width and height are the width and height of the rectangle, and the parameters raised are protruding 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 highlighted rectangle:


 g.draw3DRect(80,100,40,25,true);//Let me draw a wire frame
 g.setColor(Color.yellow); g.fill3DRect(20,70,20,30,true);// Draw a block of color 

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 surrounded by lines. Where 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) : is an ellipse filled with a predetermined color. You can also draw a circle by drawing an ellipse. When the horizontal and vertical axes are equal, the ellipse is a circle.
The following code is an example of drawing an ellipse:


 g.drawOval(10,10,60,120);//Draw the ellipse
 g.setColor(Color.cyan);g.fillOval(100,30,60,60);//Painted round piece
 g.setColor(Color.magenta);g.fillOval(15,140,100,50);// With the elliptical 

5. Draw arc
There are two ways to draw an arc:
DrawArc (int x,int y,int width,int height,int startAngle, int arcAngle) : draws an arc that is part of an ellipse. The center of the ellipse is the center of its enclosing rectangle, where the parameter is the upper-left coordinate of the enclosing rectangle (x,y), the width is the width, and the height is the heigh. The unit of the parameter startAngle is "degree", and the starting Angle 0 degree refers to the 3 o 'clock azimuth. The parameters startAngle and arcAngle mean starting from the startAngle Angle, draw the arc of the arcAngle degree counterclockwise, convention, positive degree is counterclockwise, negative degree is clockwise, such as -90 degrees is 6 o 'clock azimuth.
FillArc (int x,int y,int width, int height, int startAngle, int arcAngle) : use the setColor() method to color a part of the 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 arc line
 g.setColor(Color.yellow); g.fillArc(10,100,40,40,0,-270);//Fill an ellipse missing three quarters of the upper right corner
 g.setColor(Color.green); g.fillArc(60,110,110,60,-90,-270);// Fill an ellipse missing three quarters of the lower left corner 

6. Draw polygons
A polygon is a closed planar graph formed by joining heads and tails of several line segments. The x and y coordinates of the end points of a polygon are stored in two arrays. Here are two common ways to draw polygons:
DrawPolygon (int xpoints[],int yPoints[],int nPoints) : draws a polygon
FillPolygon (int xPoints[],int yPoints[],int nPoints) : colors the polygon with the setColor() method. Where 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.


 int px1[]={50,90,10,50};//To draw a polygon, the first and last points weigh each other
 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 use that object to draw the Polygon. The main methods of the Polygon class:

Polygon() : creates a Polygon object with no coordinate points. Polygon(int xPoints[],int yPoints[],int nPoints) : creates a Polygon object with the specified coordinate points. AddPoint () : adds a coordinate point to the Polygon object. DrawPolygon (Polygon p) : draws a Polygon. FillPolygon (Polygon p) : and the specified color to fill the Polygon.

For example, in the following code, draw a triangle and fill in a yellow triangle. Note that drawing a closed polygon with a polygon object does not require the first and last points 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 the rectangle
When there is an empty rectangle in the middle of a colored graph, a rectangle block can be filled with the background color, which is equivalent to the use of an eraser on the rectangle block.
      ClearRect (int x,int y, int width,int height) : erasing the coloring of a rectangle block specified by the parameter.
For example, the following code erases the coloring 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 map display area
A rectangle is used to represent the display area of the graph, which requires the graph to be valid within the specified range, and does not recalculate the new coordinate value. The method is clipRect(int x,int y,int width,int height), which limits the display of the graph in the specified area and does not show the excess part. When multiple restricted areas are covered, the intersection area of the restricted areas is obtained. For example, the code:


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


The equivalent of
   


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

9. Copy graphics
CopyArea (), a method of the Graphics class, can be used to copy the Graphics. The format is:
      CopyArea (int x,int y,int width,int height, int dx, int dy), dx and dy respectively represent the number of pixels pasted into the original position offset, positive value is offset to the right or down, negative value is offset to the left or up. The reference point for the displacement is to duplicate the upper-left coordinate of the rectangle.

For example, the following code shows a copy of a graph, making part of one rectangle and all of the other.


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

Applets override the update() method to clear only the circle, not the text, and the window displays 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 update() methods ",100,100);
 try{
  Thread.sleep(100);
 }
 catch(InterruptedException e){}
 repaint();
 }
 public void update(Graphics g){
 g.clearRect(i,10,200,100);//Not clear "I'm learning the update() method"
 paint(g);
 }
}

A typical drawing program inherits JFrame, defines a subclass of the JFrame window, and inherits JPanel, defines a subclass of the JPanel. Redefines the method paintComponent() in the JPanel subclass, which calls the drawing method to draw various graphs.

Application that USES 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 to red
 g.setColor(Color.green);
 g.fillRect(20, 20, 80, 40); //The actual color is a blend of green + yellow = gray
 g.setColor(Color.yellow);
 g.fillRect(60, 20, 80, 40); //The second half is yellow+yellow=read, and the first half is yellow+ grey
 g.setColor(Color.green);
 g.fillRect(20, 70, 80, 40); //The actual color is a blend of green+yellow = gray.
 g.fillRect(60, 70, 80, 40);
 //The first half is (green+yellow)+gray = background, and the second half is green+yellow = gray
 g.setColor(Color.green);
 g.drawLine(80, 100, 180, 200); //This line is green+yellow = gray
 g.drawLine(100, 100, 200, 200); //Same as above
 
 g.drawLine(140, 140, 220, 220);
 g.setColor(Color.yellow); //Analyze the following line color changes that overlap 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(" Demonstration of basic drawing methods ");
 setSize(300, 300);
 setVisible(true);
 }
}


Related articles: