Trail: 2D Graphics
Lesson: Getting Started with Graphics
The Java 2D™ API is powerful and complex. However, the vast majority of uses for the Java 2D API utilize a small subset of its capabilities encapsulated in the java.awt.Graphics class. This lesson covers the most common needs of applications developers. Less common needs are described later in the Advanced topics in the Java 2D API lesson.

Most methods of the Graphics class can by divided into two basic groups:

Methods such as setFont and setColor define how draw and fill methods render.

This figure illustrates how these methods relate to graphic objects:

This figure represents basic methods of the Graphics class

Drawing methods include:

Depending on your current need, you can choose one of the several methods in the Graphics class based on the following criteria:

Fill methods apply to geometric shapes and include fillArc, fillRect, fillOval, fillPolygon.

Whether you draw a line of text or an image, remember that in 2D graphics, every point is determined by its x and y coordinates. All of the draw and fill methods need this information, which determines where the text or image should be rendered.

For example, to draw a line, an application calls the following:

java.awt.Graphics.drawLine(int x1, int y1, int x2, int y2)

In this code (x1, y1) is the start point of the line, and (x2, y2) is the end point of the line.

So the code to draw a horizontal line is as follows:

Graphics.drawLine(20, 100, 120, 100);

This code example generates a simple image label:

This label is created by using graphic primitives and an image

ImageLabel.java contains the complete code for this example.

Previous page: Previous Lesson
Next page: Working with Geometry