Download the JDK
Search the Tutorials
Trail: 2D Graphics
« Previous • Trail • Next »
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:

> - Draw and fill methods, enabling you to render basic shapes, text, and images
> - Attributes setting methods, which affect how that drawing and filling appears

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

> This figure illustrates how these methods relate to graphic objects:

> Drawing methods include:

> - `drawString` – For drawing text

>        g.drawString("Hello", 10, 10);

> - `drawImage` – For drawing images

>        g.drawImage(img,
>                         0, 0, width, height,
>                         0, 0, imageWidth, imageHeight,
>                         null);

> - `drawLine`, `drawArc`, `drawRect`, `drawOval`, `drawPolygon` – For drawing geometric shapes

>     g2.draw(new Line2D.Double(0, 0, 30, 40));

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

> - Whether you want to render the image at the specified location and its original size or scaling it to fit inside the given rectangle
> - Whether you prefer to fill the transparent areas of the image with color or keep them transparent

> 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:

> `ImageLabel.java` contains the complete code for this example.

« Previous • Trail • Next »
Previous page: Previous Lesson
Next page: Working with Geometry