In the previous tutorial, How do I create a game window using Java Swing?, we learned how to create a game window using JFrame and a drawing area using JPanel. We also separated our application into three classes: Game, GameWindow, and GamePanel.
Now that we have a game window, it is time to learn how to draw different shapes.
Drawing is one of the most important parts of 2D game programming. Before we start working with images, sprites, and animations, we should understand how Java draws objects on the screen.
In this tutorial, we will learn how to use the Graphics2D class to draw lines, rectangles, circles, ellipses, and polygons. We will also explore colors, stroke styles, and antialiasing.
Finally, we will combine these techniques to draw a simple game character.
1. Understanding Graphics2D
Java provides the Graphics2D class as part of the Java 2D API.
The Graphics2D class extends Graphics and provides more advanced drawing capabilities.
Some of its features include:
- Drawing geometric shapes.
- Filling shapes with colors.
- Controlling line thickness and style.
- Applying antialiasing to improve visual quality.
- Drawing text.
- Transforming shapes using translation, rotation, and scaling.
In a Swing application, we normally perform custom drawing inside the paintComponent() method of a JPanel.
For example:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
try {
g2d.setColor(Color.BLUE);
g2d.fillRect(100, 100, 80, 80);
} finally {
g2d.dispose();
}
}
In this example, we create a copy of the graphics context, set the drawing color to blue, and draw a filled rectangle.
We use g.create() because we want to make changes to the graphics context without affecting the original object provided by Swing.
The copied graphics context is released by calling dispose().
Important: Never call dispose() on the original Graphics object supplied to paintComponent().
2. Preparing the project
We will continue using the Maven project from Week 02.
Our project structure remains the same:
java-2d-game/
├── pom.xml
└── src/
└── main/
└── java/
└── org/
└── kodejava/
└── game/
├── Game.java
├── GameWindow.java
└── GamePanel.java
We only need to modify the GamePanel class to experiment with different drawing operations.
The Game and GameWindow classes will remain mostly unchanged.
3. Drawing lines
Let’s start with the simplest shape: a line.
Java provides the drawLine() method to draw a line between two points.
g2d.drawLine(x1, y1, x2, y2);
The parameters represent:
x1, y1: The starting point.
x2, y2: The ending point.
For example:
g2d.setColor(Color.RED);
g2d.drawLine(50, 50, 250, 50);
This draws a horizontal red line from (50, 50) to (250, 50).
We can also draw a diagonal line:
g2d.setColor(Color.GREEN);
g2d.drawLine(50, 80, 250, 180);
Lines are useful for drawing boundaries, laser beams, grid systems, and other visual elements in games.
4. Drawing rectangles
Rectangles are among the most commonly used shapes in 2D games.
We can use rectangles to represent players, enemies, walls, platforms, and collision boundaries.
Java provides two important methods:
g2d.drawRect(x, y, width, height);
g2d.fillRect(x, y, width, height);
The difference is simple:
drawRect() draws only the outline.
fillRect() draws a filled rectangle.
For example:
g2d.setColor(Color.YELLOW);
g2d.drawRect(50, 220, 120, 80);
g2d.setColor(Color.BLUE);
g2d.fillRect(200, 220, 120, 80);
The first rectangle has a yellow outline.
The second rectangle is filled with blue.
Notice that both rectangles are positioned using the coordinates of their upper-left corners.
5. Drawing circles and ellipses
Java does not provide a separate drawCircle() method in the basic Graphics API.
Instead, we use drawOval() and fillOval().
g2d.drawOval(x, y, width, height);
g2d.fillOval(x, y, width, height);
When the width and height are equal, the shape is a circle.
For example:
g2d.setColor(Color.CYAN);
g2d.fillOval(50, 350, 80, 80);
This draws a filled circle with a diameter of 80 pixels.
To draw an ellipse, use different values for width and height:
g2d.setColor(Color.MAGENTA);
g2d.fillOval(180, 350, 140, 70);
Circles and ellipses are useful for drawing balls, planets, wheels, particles, and other rounded game objects.
6. Drawing polygons
A polygon is a shape created by connecting several points.
Examples include triangles, pentagons, and hexagons.
Java provides the drawPolygon() and fillPolygon() methods.
Let’s draw a triangle:
int[] xPoints = {400, 350, 450};
int[] yPoints = {350, 450, 450};
g2d.setColor(Color.ORANGE);
g2d.fillPolygon(
xPoints,
yPoints,
3);
The arrays contain the horizontal and vertical coordinates of the triangle’s three corners.
The final argument tells Java how many points should be used.
Polygons are particularly useful for drawing spaceships, arrows, terrain, and other objects with irregular shapes.
7. Working with colors
So far, we have used predefined colors such as:
Color.RED
Color.GREEN
Color.BLUE
Color.YELLOW
Java also allows us to create custom colors using RGB values.
RGB stands for Red, Green, and Blue.
Each component normally ranges from 0 to 255.
For example:
Color skyBlue = new Color(135, 206, 235);
Color grassGreen = new Color(34, 139, 34);
Color darkBackground = new Color(15, 23, 42);
We can use these colors just like predefined colors:
g2d.setColor(skyBlue);
g2d.fillRect(0, 0, 800, 600);
Custom colors give us greater control over the visual appearance of our games.
Using transparency
We can also create colors with transparency.
The fourth parameter of the Color constructor represents the alpha value:
Color transparentBlue =
new Color(0, 100, 255, 128);
An alpha value of 0 means fully transparent, while 255 means fully opaque.
Transparency is useful for drawing shadows, overlays, particles, and visual effects.
8. Controlling line thickness
The Graphics2D class allows us to customize how lines are drawn.
We can use the BasicStroke class to control line thickness.
For example:
g2d.setColor(Color.WHITE);
g2d.setStroke(new BasicStroke(5.0f));
g2d.drawLine(400, 50, 650, 50);
This draws a white line with a thickness of 5 pixels.
We can also customize the stroke used to draw a rectangle:
g2d.setStroke(new BasicStroke(3.0f));
g2d.drawRect(400, 100, 150, 100);
Stroke settings are useful for drawing borders, paths, and visual indicators.
Remember that a stroke setting remains active for subsequent drawing operations until it is changed.
Because our example uses a copied graphics context, changes will not affect Swing’s original graphics context.
9. Improving rendering with antialiasing
When we draw diagonal lines or circles, their edges may appear jagged.
This effect is sometimes called aliasing.
Antialiasing helps produce smoother edges by blending colors around shape boundaries.
We can enable it using a rendering hint:
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
This instructs Java 2D to use antialiasing when supported.
Antialiasing is especially useful when drawing circles, polygons, and curved shapes.
However, it also introduces additional rendering work.
For simple games, this is generally acceptable. Later, when we study performance optimization, we will explore how rendering choices affect game performance.
10. Creating a complete shapes demonstration
Now let’s combine everything we have learned into one program.
Replace the contents of GamePanel.java with the following code:
package org.kodejava.game;
import javax.swing.JPanel;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
public class GamePanel extends JPanel {
public static final int GAME_WIDTH = 800;
public static final int GAME_HEIGHT = 600;
public GamePanel() {
setPreferredSize(new Dimension(
GAME_WIDTH, GAME_HEIGHT));
setBackground(new Color(15, 23, 42));
setDoubleBuffered(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
try {
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawTitle(g2d);
drawLines(g2d);
drawRectangles(g2d);
drawCircles(g2d);
drawPolygons(g2d);
} finally {
g2d.dispose();
}
}
private void drawTitle(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
g2d.setFont(new Font(
Font.SANS_SERIF, Font.BOLD, 24));
g2d.drawString(
"Java 2D Shapes",
40, 45);
}
private void drawLines(Graphics2D g2d) {
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(3.0f));
g2d.drawLine(50, 100, 250, 100);
g2d.setColor(Color.GREEN);
g2d.drawLine(50, 130, 250, 200);
g2d.setStroke(new BasicStroke(1.0f));
}
private void drawRectangles(Graphics2D g2d) {
g2d.setColor(Color.YELLOW);
g2d.drawRect(350, 90, 120, 90);
g2d.setColor(Color.BLUE);
g2d.fillRect(500, 90, 120, 90);
}
private void drawCircles(Graphics2D g2d) {
g2d.setColor(Color.CYAN);
g2d.fillOval(50, 260, 100, 100);
g2d.setColor(Color.MAGENTA);
g2d.fillOval(200, 270, 160, 80);
}
private void drawPolygons(Graphics2D g2d) {
int[] xPoints = {500, 440, 560};
int[] yPoints = {260, 380, 380};
g2d.setColor(Color.ORANGE);
g2d.fillPolygon(xPoints, yPoints, 3);
}
}
We have organized our drawing code into several methods.
Each method handles a specific group of shapes.
This makes the program easier to read and maintain compared to placing all drawing operations directly inside paintComponent().
It also allows us to extend the program more easily.
11. Creating the GameWindow class
Our GameWindow class is almost identical to the one from Week 02.
package org.kodejava.game;
import javax.swing.JFrame;
public class GameWindow extends JFrame {
public GameWindow() {
setTitle("KodeJava 2D Shapes");
setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
setContentPane(new GamePanel());
pack();
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
}
The window uses our GamePanel as its content pane.
Because the panel defines its preferred size as 800 × 600 pixels, calling pack() creates a window with an appropriately sized drawing area.
12. Creating the Game class
The entry point remains simple:
package org.kodejava.game;
import javax.swing.SwingUtilities;
public class Game {
public static void main(String[] args) {
SwingUtilities.invokeLater(
GameWindow::new);
}
}
We use SwingUtilities.invokeLater() to create the application on the Swing Event Dispatch Thread.
13. Running the program
Open a terminal in the project directory and compile the application:
mvn clean compile
Then run the application:
java -cp target/classes org.kodejava.game.Game

You should see a window containing several geometric shapes on a dark background.
The demonstration includes two lines, an outlined rectangle, a filled rectangle, a circle, an ellipse, and a triangle.
Notice how the different drawing methods can be combined to create more complex visual objects.
14. Mini-project: Drawing a simple game character
Now that we understand basic shapes, let’s put them together to draw a simple character.
Our character will be a small robot made from rectangles, circles, and lines.
This approach is useful when we do not have image assets or sprites available.
Add the following method to GamePanel:
private void drawRobot(Graphics2D g2d) {
int x = 350;
int y = 200;
// Robot body
g2d.setColor(new Color(59, 130, 246));
g2d.fillRoundRect(
x, y + 60, 100, 120, 20, 20);
// Robot head
g2d.setColor(new Color(148, 163, 184));
g2d.fillRoundRect(
x + 10, y, 80, 70, 15, 15);
// Eyes
g2d.setColor(Color.CYAN);
g2d.fillOval(x + 25, y + 20, 15, 15);
g2d.fillOval(x + 60, y + 20, 15, 15);
// Mouth
g2d.setColor(Color.DARK_GRAY);
g2d.fillRoundRect(
x + 30, y + 48, 40, 8, 4, 4);
// Arms
g2d.setColor(new Color(100, 116, 139));
g2d.fillRect(x - 20, y + 80, 20, 70);
g2d.fillRect(x + 100, y + 80, 20, 70);
// Legs
g2d.fillRect(x + 20, y + 180, 20, 50);
g2d.fillRect(x + 60, y + 180, 20, 50);
// Antenna
g2d.setStroke(new BasicStroke(4.0f));
g2d.drawLine(
x + 50, y,
x + 50, y - 20);
g2d.setColor(Color.RED);
g2d.fillOval(x + 43, y - 30, 14, 14);
}
To display the robot instead of the shapes demonstration, update paintComponent() so that it calls drawRobot(g2d):
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
try {
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawRobot(g2d);
} finally {
g2d.dispose();
}
}

The robot is made entirely from basic geometric shapes.
We use rounded rectangles for the body and head, circles for the eyes, rectangles for the arms and legs, and a line for the antenna.
Notice that the robot’s position is controlled by two variables:
int x = 350;
int y = 200;
The other coordinates are calculated relative to these values.
For example:
g2d.fillOval(x + 25, y + 20, 15, 15);
This places the left eye 25 pixels to the right and 20 pixels below the robot’s reference position.
If we change x or y, the entire robot moves because all its components use the same reference position.
This is an important concept in game programming.
Later in the series, we will use similar techniques to move players and enemies around the screen.
15. Understanding drawing order
One important rule in Java 2D is that drawing order matters.
When several shapes overlap, shapes drawn later appear on top of shapes drawn earlier.
For example:
g2d.setColor(Color.BLUE);
g2d.fillRect(100, 100, 100, 100);
g2d.setColor(Color.RED);
g2d.fillOval(125, 125, 50, 50);
The red circle appears on top of the blue rectangle because it is drawn afterward.
If we reverse these operations, the blue rectangle will cover the red circle.
This simple rule is useful when drawing backgrounds, characters, projectiles, and other objects.
A common rendering order for a simple game is:
- Background.
- Environment and platforms.
- Game objects.
- Player and enemies.
- User interface and overlays.
We will explore more advanced rendering techniques in future tutorials.
16. Try it yourself
Before moving to the next tutorial, practice the drawing techniques we have learned.
Exercise 1: Draw a house
Use rectangles, lines, and polygons to draw a simple house.
Try adding a roof, door, and two windows.
Exercise 2: Draw a traffic light
Draw a vertical rectangle containing three circles.
Use red, yellow, and green colors for the lights.
Exercise 3: Customize the robot
Modify the robot’s appearance by changing its colors, dimensions, and facial features.
Try adding hands or different-shaped feet.
Exercise 4: Move the robot
Change the values of x and y inside drawRobot().
Observe how all the robot’s parts move together.
As an additional challenge, try moving the robot’s position to the center of the game panel.
17. Summary
In this tutorial, we learned how to draw different shapes using the Java 2D API.
We covered:
- Using
Graphics2D for custom drawing.
- Drawing lines with
drawLine().
- Drawing rectangles with
drawRect() and fillRect().
- Drawing circles and ellipses with
drawOval() and fillOval().
- Drawing polygons using arrays of coordinates.
- Creating custom colors with RGB values.
- Controlling line thickness using
BasicStroke.
- Improving visual quality using antialiasing.
- Combining shapes to draw a simple game character.
- Understanding how drawing order affects overlapping shapes.
We also created a simple robot character using only Java 2D drawing operations.
This demonstrates that we can create interesting game objects without using image files.
In the next tutorial, How do I understand coordinates in a 2D game?, we will explore the coordinate system in greater detail.
We will learn how to position objects, calculate distances, work with relative coordinates, and understand how coordinates affect game movement.
Maven Dependencies
Java Swing and the Java 2D API are included in the Java Development Kit.
No external dependencies are required for this tutorial.
Our Maven project uses Java 25 and the Maven Compiler Plugin.
Here is the complete pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.kodejava</groupId>
<artifactId>java-2d-game</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
</plugins>
</build>
</project>
Required Maven dependencies: None.
Build plugin:
org.apache.maven.plugins:maven-compiler-plugin:3.14.1
References