Java Graphics  «Prev  Next»

Lesson 3 Drawing graphics primitives
ObjectiveDraw Graphics primitives using the AWT Graphics Class

Draw Graphics primitives using the AWT Graphics Class

You might be surprised by what you can draw with simple graphics primitives, which consist of lines, rectangles, squares, ovals, circles, polygons, and arcs. The Graphics class includes methods that allow you to draw each of the graphics primitives.

Draw Lines

The drawLine() method is used to draw lines:

public void drawLine(int x1, int y1, int x2, int y2)

The parameters to the drawLine() method indicate the starting point (x1, y1) and ending point (x2, y2) for the line.
The following code shows how to draw a diagonal line using the drawLine() method:

public void paint(Graphics g) {
  g.drawLine(0, 0, 75, 75);
}

Rectangles


The drawRect() method is used to draw rectangles:
public void drawRect(int x, int y, int width, int height)

The parameters to the drawRect() method indicate the upper left corner of the rectangle (x, y) and the width and height of the rectangle.
The following code shows how to draw a rectangle twice as wide as it is tall, using the drawRect()method:

public void paint(Graphics g) {
  g.drawRect(0, 0, 100, 50);
}

You can draw filled rectangles with the fillRect() method.

Ovals

The drawOval() method is used to draw ovals, and works very much like the drawRect() method:

public void drawOval(int x, int y, int width, int height)

The following code shows how to draw an oval that is three times as tall as it is wide, using the drawOval() method:
public void paint(Graphics g) {
  g.drawOval(0, 0, 100, 300);
}

Draw squares and circles with the drawRect() and drawOval() methods respectively by providing the same value for the width and height.

Drawing Graphics Exercise

Try drawing graphics primitives in this exercise.
Drawing Graphics - Exercise