How do I understand coordinates in a 2D game?

Java 2D Game Programming Banner

In the previous tutorial, How do I draw 2D shapes using Graphics2D?, we learned how to draw lines, rectangles, circles, and polygons using Java Swing. We also created a simple robot character using geometric shapes.

However, there is something important behind every drawing operation: coordinates.

Coordinates determine where objects appear on the screen. They are also essential for player movement, collision detection, camera scrolling, and many other game mechanics.

In this tutorial, we will learn how the Java 2D coordinate system works and create an interactive application that displays object coordinates.

By the end of this tutorial, you will understand how to:

  • Work with X and Y coordinates.
  • Understand the direction of the coordinate axes.
  • Position objects using absolute and relative coordinates.
  • Calculate the center of an object.
  • Keep an object inside the game area.
  • Calculate distances between objects.
  • Convert mouse positions into game object positions.

We will continue using Java 25, Java Swing, and Apache Maven.

1. Understanding the coordinate system

In Java Swing, the default coordinate system starts at the upper-left corner of a component.

This location is called the origin and has the coordinates:

(0, 0)

The horizontal axis is called the X-axis, and the vertical axis is called the Y-axis.

The important difference from a traditional mathematical graph is that Y increases downward.

For example, in an 800 × 600 game panel:

Coordinate Location
(0, 0) Upper-left corner
(400, 300) Center
(100, 100) 100 pixels right and 100 pixels down
(799, 599) Bottom-right pixel

The last example assumes integer pixel coordinates in an 800 × 600 drawing area.

Understanding these directions is essential because moving an object upward requires decreasing its Y coordinate.

Moving it downward requires increasing its Y coordinate.

2. Drawing an object at a specific position

Let’s start with a simple rectangle.

g2d.fillRect(100, 150, 50, 50);

The fillRect() method accepts four parameters:

fillRect(x, y, width, height);

The first two parameters represent the position of the rectangle’s upper-left corner.

The remaining parameters define its size.

In our example:

int x = 100;
int y = 150;
int width = 50;
int height = 50;

The rectangle begins at coordinate (100, 150) and extends 50 pixels to the right and 50 pixels downward.

We can make our program easier to understand by storing these values in variables:

int playerX = 100;
int playerY = 150;
int playerWidth = 50;
int playerHeight = 50;

g2d.fillRect(
        playerX,
        playerY,
        playerWidth,
        playerHeight);

This approach is useful because the object’s position can be changed without modifying the drawing statement.

Later, we will update these variables to make our player move.

3. Understanding absolute and relative coordinates

There are two useful ways to position objects: absolute coordinates and relative coordinates.

Absolute coordinates

Absolute coordinates represent positions relative to the coordinate system’s origin.

For example:

g2d.fillRect(100, 100, 50, 50);
g2d.fillRect(300, 200, 50, 50);

Both rectangles have fixed positions.

Relative coordinates

Relative coordinates describe positions based on another object’s location.

Consider the robot we created in previuos tutorial.

Instead of assigning independent coordinates to its eyes, arms, and legs, we calculated their positions relative to the robot’s position.

For example:

int robotX = 200;
int robotY = 150;

g2d.fillRect(robotX, robotY, 100, 100);

g2d.fillOval(
        robotX + 20,
        robotY + 25,
        15,
        15);

g2d.fillOval(
        robotX + 65,
        robotY + 25,
        15,
        15);

The rectangle represents the robot’s head, and the circles represent its eyes.

If we change robotX or robotY, the eyes move with the head.

This makes relative coordinates extremely useful for drawing complex objects.

4. Calculating the center of an object

In many games, we need to know the center of an object rather than its upper-left corner.

Consider a player with the following properties:

int playerX = 100;
int playerY = 150;
int playerWidth = 50;
int playerHeight = 50;

We can calculate the player’s center using:

double centerX = playerX + playerWidth / 2.0;
double centerY = playerY + playerHeight / 2.0;

The result is:

centerX = 125
centerY = 175

Why is this useful?

The center of an object can help us determine distances, rotate objects, position projectiles, and detect certain types of collisions.

For example, if we want to draw a small circle at the player’s center:

g2d.setColor(Color.RED);

g2d.fillOval(
        (int) centerX - 5,
        (int) centerY - 5,
        10,
        10);

We subtract 5 from each coordinate because fillOval() also uses the upper-left corner of the oval’s bounding rectangle.

The result is a red circle centered inside the player.

5. Positioning an object in the center of the game window

Suppose our game panel is 800 pixels wide and 600 pixels high.

Our player is a 50 × 50 square.

To center the player, calculate:

int playerX = (800 - 50) / 2;
int playerY = (600 - 50) / 2;

The resulting position is:

playerX = 375
playerY = 275

The player’s center is located at (400, 300).

Instead of hardcoding the panel dimensions, we can use:

int playerX = (getWidth() - playerWidth) / 2;
int playerY = (getHeight() - playerHeight) / 2;

This approach is useful when the game window can be resized.

Note: getWidth() and getHeight() return the actual dimensions of the component. These values may be zero before the component has been laid out.

For this reason, we normally calculate positions based on these methods after the panel has been displayed, or during painting when its dimensions are available.

6. Keeping an object inside the game area

Imagine that our player can move around the screen.

Without boundaries, the player might move outside the visible game area.

We can prevent this by limiting its position.

For example:

playerX = Math.max(
        0,
        Math.min(playerX, gameWidth - playerWidth));

playerY = Math.max(
        0,
        Math.min(playerY, gameHeight - playerHeight));

Let’s understand the first expression.

Math.min(playerX, gameWidth - playerWidth)

This ensures that the player’s X position does not exceed the right boundary.

Then:

Math.max(0, ...)

Prevents the position from becoming negative.

We use the same approach for the Y coordinate.

This operation is commonly called clamping.

Clamping values is a useful technique in game programming because it restricts numbers to a specific range.

7. Calculating distances between objects

Another important use of coordinates is calculating the distance between two points.

Suppose we have two objects located at:

double x1 = 100;
double y1 = 100;

double x2 = 400;
double y2 = 300;

We can calculate the distance using the Pythagorean theorem.

The formula is:

d = \sqrt{(x_2-x_1)^2 + (y_2-y_1)^2}

Java provides the Math.hypot() method to perform this calculation:

double dx = x2 - x1;
double dy = y2 - y1;

double distance = Math.hypot(dx, dy);

For the points in our example, the distance is approximately:

360.56 pixels

Distance calculations are useful in many game mechanics.

For example, we can use them to determine whether a player is close enough to collect an item, interact with an object, or trigger an enemy’s detection range.

For circular objects, distances between centers are also useful for collision detection.

8. Creating an interactive coordinate explorer

Now that we understand the basic concepts, let’s create an interactive application.

Our application will display a player represented by a blue square.

When the user clicks anywhere inside the game panel, the player moves to the clicked position.

The application will also display:

  • The player’s X and Y coordinates.
  • The player’s center coordinates.
  • The latest mouse click coordinates.
  • The distance between the player and the mouse cursor.

This will help us visualize how coordinates work in Java 2D.

Project structure

We will continue using the same project structure:

java-2d-game/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── org/
                └── kodejava/
                    └── game/
                        ├── Game.java
                        ├── GameWindow.java
                        └── GamePanel.java

Creating GamePanel.java

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.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

public class GamePanel extends JPanel {

    public static final int GAME_WIDTH = 800;
    public static final int GAME_HEIGHT = 600;

    private static final int PLAYER_SIZE = 50;

    private int playerX = 375;
    private int playerY = 275;

    private Point mousePosition = new Point(400, 300);
    private Point lastClick = new Point(400, 300);

    public GamePanel() {
        setPreferredSize(new Dimension(
                GAME_WIDTH, GAME_HEIGHT));

        setBackground(new Color(15, 23, 42));
        setDoubleBuffered(true);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                movePlayerTo(e.getX(), e.getY());
            }
        });

        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                mousePosition = e.getPoint();
                repaint();
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                mousePosition = e.getPoint();
                repaint();
            }
        });
    }

    private void movePlayerTo(int mouseX, int mouseY) {
        lastClick = new Point(mouseX, mouseY);
        mousePosition = new Point(mouseX, mouseY);

        playerX = mouseX - PLAYER_SIZE / 2;
        playerY = mouseY - PLAYER_SIZE / 2;

        int maxX = Math.max(0, getWidth() - PLAYER_SIZE);
        int maxY = Math.max(0, getHeight() - PLAYER_SIZE);

        playerX = Math.max(0, Math.min(playerX, maxX));
        playerY = Math.max(0, Math.min(playerY, maxY));

        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g.create();

        try {
            g2d.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            drawGrid(g2d);
            drawPlayer(g2d);
            drawMouseMarker(g2d);
            drawInformation(g2d);
        } finally {
            g2d.dispose();
        }
    }

    private void drawGrid(Graphics2D g2d) {
        g2d.setColor(new Color(51, 65, 85));
        g2d.setStroke(new BasicStroke(1.0f));

        int gridSize = 50;

        for (int x = 0; x < getWidth(); x += gridSize) {
            g2d.drawLine(x, 0, x, getHeight());
        }

        for (int y = 0; y < getHeight(); y += gridSize) {
            g2d.drawLine(0, y, getWidth(), y);
        }
    }

    private void drawPlayer(Graphics2D g2d) {
        g2d.setColor(new Color(59, 130, 246));

        g2d.fillRoundRect(
                playerX,
                playerY,
                PLAYER_SIZE,
                PLAYER_SIZE,
                10,
                10);

        double centerX = playerX + PLAYER_SIZE / 2.0;
        double centerY = playerY + PLAYER_SIZE / 2.0;

        g2d.setColor(Color.WHITE);

        g2d.fillOval(
                (int) centerX - 4,
                (int) centerY - 4,
                8,
                8);
    }

    private void drawMouseMarker(Graphics2D g2d) {
        g2d.setColor(new Color(250, 204, 21));

        int x = mousePosition.x;
        int y = mousePosition.y;

        g2d.drawOval(x - 6, y - 6, 12, 12);
        g2d.drawLine(x - 12, y, x + 12, y);
        g2d.drawLine(x, y - 12, x, y + 12);
    }

    private void drawInformation(Graphics2D g2d) {
        g2d.setFont(new Font(
                Font.MONOSPACED, Font.PLAIN, 14));

        double centerX = playerX + PLAYER_SIZE / 2.0;
        double centerY = playerY + PLAYER_SIZE / 2.0;

        double distance = Math.hypot(
                mousePosition.x - centerX,
                mousePosition.y - centerY);

        // Panel background for readable information
        g2d.setColor(new Color(15, 23, 42, 235));
        g2d.fillRoundRect(15, 15, 410, 145, 12, 12);

        g2d.setColor(Color.WHITE);

        g2d.drawString(
                "Java 2D Coordinate Explorer",
                30, 40);

        g2d.drawString(
                "Player: (" + playerX + ", " + playerY + ")",
                30, 65);

        g2d.drawString(
                "Center: (" + centerX + ", " + centerY + ")",
                30, 85);

        g2d.drawString(
                "Last click: (" + lastClick.x +
                        ", " + lastClick.y + ")",
                30, 105);

        g2d.drawString(
                "Distance to mouse: %.2f px"
                        .formatted(distance),
                30, 125);

        g2d.drawString(
                "Click anywhere to move the player",
                30, 145);
    }
}

How does the mouse listener work?

The following code registers a mouse listener:

addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        movePlayerTo(e.getX(), e.getY());
    }
});

Whenever the user presses a mouse button inside the panel, Swing invokes the mousePressed() method.

The event object provides the mouse coordinates relative to the component.

We use these coordinates to update the player’s position.

Why subtract half the player size?

Inside movePlayerTo(), we calculate the player position using:

playerX = mouseX - PLAYER_SIZE / 2;
playerY = mouseY - PLAYER_SIZE / 2;

Remember that fillRect() and fillRoundRect() expect the upper-left corner of the rectangle.

If we assigned the mouse coordinates directly to playerX and playerY, the player’s upper-left corner would appear at the mouse position.

By subtracting half the player’s width and height, we place the center of the player at the clicked position.

This works exactly for a player with an even size such as our 50 × 50 square, provided it does not need to be clamped at the panel boundaries.

Why call repaint()?

After updating the player’s position, we call:

repaint();

This requests that Swing repaint the component.

The repaint operation is scheduled by Swing rather than necessarily happening immediately.

When Swing processes the repaint request, our paintComponent() method is called, and the player is drawn at its updated position.

The repaint() method is one of the most important methods when creating interactive Swing applications.

Later, when we introduce a game loop, we will request repaints as the game state changes over time.

Understanding mouse movement

We also register a mouse motion listener.

addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseMoved(MouseEvent e) {
        mousePosition = e.getPoint();
        repaint();
    }
});

The mouseMoved() method is invoked when the mouse moves inside the panel without a button pressed.

We store the current mouse position and request a repaint.

This allows the application to display the distance between the player and the mouse cursor.

The example also handles mouseDragged() so that the marker updates while a mouse button is held down.

9. Creating GameWindow.java

The GameWindow class remains similar to the one from Week 02.

package org.kodejava.game;

import javax.swing.JFrame;

public class GameWindow extends JFrame {

    public GameWindow() {
        setTitle("Java 2D Coordinate Explorer");

        setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);

        setContentPane(new GamePanel());

        pack();
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }
}

We use the GamePanel as the content pane and let pack() size the frame according to the panel’s preferred dimensions.

10. Creating Game.java

Our application entry point remains unchanged:

package org.kodejava.game;

import javax.swing.SwingUtilities;

public class Game {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(GameWindow::new);
    }
}

Using SwingUtilities.invokeLater() ensures that our Swing window is created on the Event Dispatch Thread.

11. Running the program

Open a terminal in the project directory and compile the application:

mvn clean compile

Then run it:

java -cp target/classes org.kodejava.game.Game

Coordinate Explorer

The program opens a window displaying a coordinate grid and a blue square representing the player.

Move your mouse around the game panel. You will see a yellow crosshair following the cursor.

Click anywhere in the panel to move the player to that location.

The information panel displays the player’s position, center coordinates, last click position, and distance to the mouse.

Try clicking near the edges of the game window.

Notice that the player remains inside the visible area because we clamp its position.

12. Understanding coordinate boundaries

Let’s look more closely at how boundaries work.

For an 800 × 600 game area and a 50 × 50 player:

Minimum X = 0
Maximum X = 800 - 50 = 750

Minimum Y = 0
Maximum Y = 600 - 50 = 550

This means the player’s upper-left corner must remain within the following range:

0 <= playerX <= 750
0 <= playerY <= 550

If we allowed playerX to become 780, only part of the player would be visible.

By limiting the position to 750, we ensure that the entire 50-pixel-wide player fits inside the 800-pixel-wide panel.

These calculations become especially important when implementing player movement.

13. Understanding coordinate spaces

So far, we have worked with coordinates relative to a single JPanel.

In larger games, however, we often use several coordinate spaces.

The most common ones are:

Screen coordinates

These describe positions on the physical display or within a window.

Component coordinates

These describe positions relative to a Swing component, such as our GamePanel.

World coordinates

These describe positions inside the game world, which can be larger than the visible game area.

For example, imagine a platform game with a world that is 5,000 pixels wide but a window that is only 800 pixels wide.

A player might have a world X coordinate of 2,000, even though the visible window is only 800 pixels wide.

We can use a camera position to convert world coordinates into screen coordinates.

A simplified conversion looks like this:

int screenX = worldX - cameraX;
int screenY = worldY - cameraY;

We will explore this concept in greater detail when we build scrolling game worlds and tile-based maps.

For now, our game uses component coordinates directly.

14. Try it yourself

Before continuing to the next tutorial, try the following exercises.

Exercise 1: Change the player size

Modify:

private static final int PLAYER_SIZE = 50;

Try using 80 or 100 instead.

Observe how the boundary calculations keep the larger player inside the game area.

Exercise 2: Display the player’s bottom-right coordinate

Calculate the bottom-right corner:

int right = playerX + PLAYER_SIZE;
int bottom = playerY + PLAYER_SIZE;

Display these values in the information panel.

Exercise 3: Draw a line from the player to the mouse

Inside paintComponent(), add a method that draws a line between the player’s center and the current mouse position.

For example:

g2d.setColor(Color.GREEN);

g2d.drawLine(
        playerX + PLAYER_SIZE / 2,
        playerY + PLAYER_SIZE / 2,
        mousePosition.x,
        mousePosition.y);

Remember that drawing order matters.

Draw the line before drawing the player if you want the player to appear on top of it.

Exercise 4: Create a collectible object

Add a yellow circle at position (600, 400).

Calculate the distance between the player’s center and the circle’s center.

Display a message when the distance is less than 60 pixels.

For this exercise, we are using a distance threshold rather than checking whether the actual shapes overlap.

We will learn about collision detection in a later tutorial.

15. Summary

In this tutorial, we learned how coordinates work in Java 2D game programming.

We covered:

  • The Java Swing coordinate system.
  • The difference between X and Y coordinates.
  • Absolute and relative positioning.
  • Calculating the center of an object.
  • Centering an object in the game window.
  • Keeping objects inside the visible game area.
  • Calculating distances using Math.hypot().
  • Handling mouse coordinates.
  • Updating object positions and requesting repaints.
  • Understanding component, screen, and world coordinates.

We also created an interactive coordinate explorer that allows us to move a player around the game area using the mouse.

These concepts form the foundation for player movement, collision detection, and camera systems.

In the next tutorial, How do I handle keyboard input in a Java game?, we will learn how to use keyboard events to control our game objects.

We will introduce Swing key bindings and create a simple input system that prepares our project for player movement.

Maven Dependencies

Java Swing, Java 2D, and the event-handling classes used in this tutorial are included in the JDK.

No external game libraries are required.

The complete pom.xml is shown below:

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

How do I draw 2D shapes using Graphics2D?

Java 2D Game Programming Banner

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

2D Shapes

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

Drawing Robot Shape

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:

  1. Background.
  2. Environment and platforms.
  3. Game objects.
  4. Player and enemies.
  5. 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

How do I create a game window using Java Swing?

Java 2D Game Programming Banner

In the previous tutorial, How do I get started with 2D game programming in Java?, we created our first game window and drew a simple rectangle using Java Swing.

Our first example placed everything inside a single Java class. This approach is useful when learning the basics, but as we add more features, our game will become harder to maintain.

In this tutorial, we will improve the structure of our project by separating the game window from the drawing area.

By the end of this tutorial, you will learn how to:

  • Create a game window using JFrame.
  • Create a drawing area using JPanel.
  • Separate the game window and rendering responsibilities.
  • Configure the window size, title, and close operation.
  • Draw a simple player object using Graphics2D.
  • Start a Swing application using the Event Dispatch Thread.

We will continue using Java 25, Java Swing, and Apache Maven.

1. Understanding the game window

Before writing the code, let’s understand the two main components we will use.

JFrame — The game window

JFrame represents the main window of our desktop application.

It provides a title bar, borders, and window controls such as minimize, maximize, and close.

In our game, the frame acts as a container for the drawing area.

JPanel — The drawing area

JPanel is a Swing component that can be used to organize other components or display custom graphics.

We will extend JPanel and override its paintComponent() method to draw our game objects.

Our application will have three classes:

Class Responsibility
Game Starts the application
GameWindow Creates and configures the main window
GamePanel Draws the game content

This separation makes our code easier to understand and extend.

Later, we can add classes for player movement, keyboard input, game objects, and collision detection without putting everything inside a single class.

2. Creating the Maven project

Create a Maven project named java-2d-game.

We will organize the project using the following structure:

java-2d-game/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── org/
                └── kodejava/
                    └── game/
                        ├── Game.java
                        ├── GameWindow.java
                        └── GamePanel.java

All three classes belong to the org.kodejava.game package.

If you are continuing from Week 01, replace the previous Game.java implementation and add the two new classes.

3. Creating the GamePanel class

Let’s start with the drawing area.

Create a file named GamePanel.java:

package org.kodejava.game;

import javax.swing.JPanel;
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);

            drawWelcomeMessage(g2d);
            drawPlayer(g2d);
        } finally {
            g2d.dispose();
        }
    }

    private void drawWelcomeMessage(Graphics2D g2d) {
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font(
                Font.SANS_SERIF, Font.BOLD, 24));

        String message = "Welcome to Java 2D Game!";

        int textWidth = g2d.getFontMetrics()
                .stringWidth(message);

        int x = (GAME_WIDTH - textWidth) / 2;
        int y = 150;

        g2d.drawString(message, x, y);
    }

    private void drawPlayer(Graphics2D g2d) {
        int playerSize = 50;

        int x = (GAME_WIDTH - playerSize) / 2;
        int y = (GAME_HEIGHT - playerSize) / 2;

        g2d.setColor(new Color(96, 165, 250));
        g2d.fillRect(x, y, playerSize, playerSize);
    }
}

Understanding setPreferredSize()

The following code defines the preferred size of our game panel:

setPreferredSize(new Dimension(
        GAME_WIDTH, GAME_HEIGHT));

We use an 800 × 600 pixel drawing area.

Notice that this defines the size of the game panel, not necessarily the entire desktop window.

The outer window also includes decorations such as the title bar and borders.

Understanding paintComponent()

The paintComponent() method is responsible for drawing the content of our panel.

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    try {
        drawWelcomeMessage(g2d);
        drawPlayer(g2d);
    } finally {
        g2d.dispose();
    }
}

The Graphics object represents the drawing context supplied by Swing.

We create a separate graphics context using g.create() so that changes to rendering settings do not affect the original context.

Calling dispose() releases the resources associated with our copy.

Important: We must not call dispose() on the original Graphics object provided by Swing.

Why do we call super.paintComponent()?

The following statement should usually be the first operation in our overridden painting method:

super.paintComponent(g);

It allows Swing to perform the standard painting behavior for the component.

Since our panel is opaque and has a background color, this also allows Swing to clear the drawing area before we render our objects.

What is double buffering?

Double buffering is a technique that helps reduce flickering while drawing graphics.

Instead of exposing partially drawn frames directly to the screen, the drawing operations can be performed using an offscreen buffer.

The completed image is then displayed.

In our example, we call:

setDoubleBuffered(true);

Swing already uses double buffering for normal painting in common configurations, so this call makes our intention explicit.

We do not need to create a separate image buffer manually.

Later in the series, we will learn more about smooth animation and efficient rendering.

4. Creating the GameWindow class

Now we need a class that creates and configures the main window.

Create GameWindow.java:

package org.kodejava.game;

import javax.swing.JFrame;

public class GameWindow extends JFrame {

    public GameWindow() {
        setTitle("KodeJava 2D Game");

        setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);

        setContentPane(new GamePanel());

        pack();
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }
}

This class extends JFrame, so it inherits the functionality of a Swing window.

Let’s examine its configuration.

Setting the window title

setTitle("KodeJava 2D Game");

This determines the text displayed in the window’s title bar.

Configuring the close operation

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This tells Swing to exit the application when the user closes the window.

For our simple standalone game, this behavior is appropriate.

Adding the GamePanel

setContentPane(new GamePanel());

This places our custom game panel inside the frame as its content pane.

The GameWindow class does not need to know how the panel draws its contents.

Its responsibility is to manage the window.

Using pack()

pack();

The pack() method sizes the frame according to the preferred sizes of its contained components.

Because our GamePanel requests an 800 × 600 drawing area, pack() calculates a suitable frame size that also accounts for the window’s decorations.

This is generally better than using setSize(800, 600) when we want the actual game area to have a specific size.

Centering the game window

setLocationRelativeTo(null);

This positions the window in the center of the screen.

Preventing window resizing

setResizable(false);

For now, we will use a fixed-size window.

This makes it easier to understand coordinates and object positions.

We can introduce resizable windows and scaling after learning more about rendering.

5. Creating the Game class

Finally, create the application’s entry point.

Create Game.java:

package org.kodejava.game;

import javax.swing.SwingUtilities;

public class Game {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(GameWindow::new);
    }
}

This is now a very small class.

Its only responsibility is to start our application.

Why use SwingUtilities.invokeLater()?

Swing applications use the Event Dispatch Thread (EDT) to process events and interact with GUI components.

The following code schedules creation of our window on the EDT:

SwingUtilities.invokeLater(GameWindow::new);

This is equivalent to:

SwingUtilities.invokeLater(() -> {
    new GameWindow();
});

A constructor reference is simply a more concise way to express the same operation.

Creating and updating Swing components on the EDT helps avoid threading problems.

When we introduce a game loop, we will also learn why long-running calculations should not block this thread.

6. Running the game

We now have three Java classes:

  • Game.java
  • GameWindow.java
  • GamePanel.java

Compile the project:

mvn clean compile

Then run the application from your IDE.

You can also execute it from the command line:

java -cp target/classes org.kodejava.game.Game

If everything works correctly, a window titled KodeJava 2D Game will appear.

Game Window

Inside the window, you should see:

  • A dark background.
  • A white welcome message.
  • A blue square positioned in the center of the drawing area.

The blue square represents our player.

It does not move yet, but our project now has a better structure for future development.

7. Understanding the rendering coordinates

Java 2D uses a coordinate system where the origin (0, 0) is located at the upper-left corner of the component.

The horizontal coordinate increases toward the right, and the vertical coordinate increases downward.

For example:

g2d.fillRect(100, 150, 50, 50);

This draws a rectangle with its top-left corner at (100, 150).

Its width and height are both 50 pixels.

In our drawPlayer() method, we use a simple calculation to position the player in the center:

int playerSize = 50;

int x = (GAME_WIDTH - playerSize) / 2;
int y = (GAME_HEIGHT - playerSize) / 2;

For an 800 × 600 drawing area and a 50 × 50 player, the calculated position is:

x = (800 - 50) / 2 = 375
y = (600 - 50) / 2 = 275

This places the rectangle’s top-left corner at (375, 275).

Its center is therefore at (400, 300), which is the center of our game area.

We will explore coordinates in more detail in Week 04.

8. Why separate GameWindow and GamePanel?

You might wonder why we need several classes when the previous example worked with only one.

The main reason is separation of responsibilities.

GameWindow handles the desktop window, while GamePanel handles the drawing area.

This separation becomes more valuable as we develop larger games.

For example, later we can extend our project with additional classes:

org.kodejava.game
├── Game.java
├── GameWindow.java
├── GamePanel.java
├── Player.java
├── Enemy.java
└── GameLoop.java

Each class will have a specific responsibility.

This approach makes our code easier to read, test, maintain, and reuse.

For a simple example, three classes may seem unnecessary. However, we are preparing a foundation for projects that will eventually include movement, animation, collision detection, and game logic.

9. Try it yourself

Before moving to the next tutorial, try these exercises.

Exercise 1 — Change the game resolution

Modify the dimensions in GamePanel:

public static final int GAME_WIDTH = 1024;
public static final int GAME_HEIGHT = 768;

Run the application again.

Notice how pack() automatically adjusts the window to accommodate the new preferred size.

Exercise 2 — Change the background color

Replace:

setBackground(new Color(15, 23, 42));

with:

setBackground(Color.DARK_GRAY);

Exercise 3 — Draw another object

Add the following code inside drawPlayer():

g2d.setColor(Color.YELLOW);
g2d.fillOval(100, 100, 40, 40);

Now the game displays both a square and a circle.

Exercise 4 — Allow window resizing

Change:

setResizable(false);

to:

setResizable(true);

Try resizing the window.

Notice that our player position is still calculated using the fixed values GAME_WIDTH and GAME_HEIGHT.

This means the player will not automatically remain centered when the window becomes larger.

As an additional challenge, try using getWidth() and getHeight() from GamePanel when calculating the player position.

10. Summary

In this tutorial, we improved the structure of our Java 2D game project.

We learned how to:

  • Create a main game window using JFrame.
  • Create a custom drawing panel using JPanel.
  • Separate window management from rendering.
  • Configure window dimensions and positioning.
  • Draw text and objects using Graphics2D.
  • Start Swing components on the Event Dispatch Thread.
  • Understand the basic coordinate system used for drawing.

Our game is still simple, but we now have a foundation that can grow into a complete 2D game.

In the next tutorial, How do I draw 2D shapes using Graphics2D?, we will learn how to draw lines, rectangles, circles, and other shapes, as well as how to use colors and rendering settings.

Maven Dependencies

Java Swing and Java 2D are included in the standard Java Development Kit as part of the java.desktop module.

We do not need any external libraries for this tutorial.

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

How do I get started with 2D game programming in Java?

Java 2D Game Programming Banner

Game programming is a fun way to learn Java because it combines programming concepts with visual results. Instead of writing programs that only print text to the console, we can create characters, draw objects, and eventually build interactive games.

In this tutorial, we will take our first step into 2D game programming using Java Swing. We will create a simple game window and draw a player represented by a blue square.

This is the first article in our 2D Game Programming with Java Swing series, where we will learn to build games from scratch without relying on an external game engine.

What is 2D game programming?

A 2D game is a game where objects are positioned in a two-dimensional space using horizontal and vertical coordinates.

Some familiar examples include Pong, Snake, Breakout, and traditional platform games.

Most 2D games share several important concepts:

  • Game window: The area where the game is displayed.
  • Game objects: Players, enemies, obstacles, and other elements.
  • Rendering: Drawing game objects on the screen.
  • Input handling: Responding to keyboard and mouse input.
  • Game loop: Continuously updating and displaying the game.
  • Collision detection: Detecting when objects touch or overlap.

We will explore these concepts one at a time throughout the series.

Why use Java Swing?

Java Swing is a GUI toolkit included in the Java Development Kit (JDK). Although it was primarily designed for desktop applications, we can also use it to build simple 2D games.

Swing provides several useful classes:

Class Purpose
JFrame Creates the main game window
JPanel Provides an area for drawing game objects
Graphics Offers basic drawing operations
Graphics2D Provides more advanced 2D drawing capabilities
Timer Can schedule periodic updates for simple games

One advantage of using Swing is that we do not need to install an additional game engine.

By building games directly with Swing and Java 2D, we can better understand the fundamental techniques used in game development.

What do we need?

Before getting started, make sure you have:

  • Java Development Kit (JDK) 25
  • Apache Maven
  • A Java IDE such as IntelliJ IDEA, Eclipse, or NetBeans

We will use Java 25, an LTS release, for this series.

To verify your Java installation, open a terminal and run:

java -version

Then check your Maven installation:

mvn -version

Creating our first game project

Create a Maven project named java-2d-game.

Our initial project structure will look like this:

java-2d-game/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── org/
                └── kodejava/
                    └── game/
                        └── Game.java

We will start with a single Java class to keep the example easy to understand.

As our game becomes more complex, we will introduce additional classes to organize the code.

Creating the game window

Let’s create a Java class named Game.java.

package org.kodejava.game;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class Game extends JPanel {

    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    public Game() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(Color.BLACK);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g.create();

        try {
            g2d.setColor(Color.BLUE);
            g2d.fillRect(100, 100, 50, 50);
        } finally {
            g2d.dispose();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("My First Java 2D Game");

            frame.setDefaultCloseOperation(
                    JFrame.EXIT_ON_CLOSE);

            frame.add(new Game());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setResizable(false);
            frame.setVisible(true);
        });
    }
}

When we run this program, a window will appear with a black background and a blue square.

The square represents our first game object. It does not move yet, but it provides a starting point for the next tutorials.

Game Window
Game Window

Understanding the code

Let’s examine the important parts of our program.

Extending JPanel

public class Game extends JPanel {

By extending JPanel, our class becomes a Swing component that can display custom graphics.

We can override its painting method to draw our game objects.

Setting the game area

setPreferredSize(new Dimension(800, 600));
setBackground(Color.BLACK);

Here, we define a preferred game area of 800 pixels wide and 600 pixels high.

We also set the background color to black.

Drawing the player

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    try {
        g2d.setColor(Color.BLUE);
        g2d.fillRect(100, 100, 50, 50);
    } finally {
        g2d.dispose();
    }
}

The paintComponent() method is called by Swing when the component needs to be painted.

We call super.paintComponent(g) first so that Swing can perform its standard component painting.

Next, we create a copy of the graphics context and use Graphics2D to draw a rectangle.

The fillRect() method accepts four parameters:

fillRect(x, y, width, height);

In our example:

  • x = 100: The horizontal position.
  • y = 100: The vertical position.
  • width = 50: The rectangle width.
  • height = 50: The rectangle height.

The rectangle is drawn at position (100, 100) and has a size of 50 × 50 pixels.

Finally, we dispose of the copied graphics context to release its associated resources.

Creating the main window

JFrame frame = new JFrame("My First Java 2D Game");

The JFrame class creates the main desktop window.

We then add our game panel:

frame.add(new Game());

The pack() method adjusts the window size based on the preferred size of its contents.

We use setLocationRelativeTo(null) to center the window on the screen.

Understanding SwingUtilities.invokeLater()

SwingUtilities.invokeLater(() -> {
    // Create and display the game window
});

Swing uses a special thread called the Event Dispatch Thread (EDT) to process GUI events and update components.

Using SwingUtilities.invokeLater() ensures that our Swing interface is created on this thread.

This is important because most Swing components are not thread-safe.

Later in this series, we will learn how to coordinate game updates with Swing rendering.

Running the program

First, compile the project using Maven:

mvn compile

Then run the main class from your IDE.

Alternatively, after compiling, you can run it from the project root using:

java -cp target/classes org.kodejava.game.Game

You should see an 800 × 600 game area with a blue square displayed near the upper-left corner.

Congratulations! You have created your first 2D game window in Java.

Although the square is not interactive yet, we already have two essential components of a game: a window and a rendering area.

Try it yourself

Before moving to the next tutorial, try making a few changes to the program.

Exercise 1: Change the player color

Replace:

g2d.setColor(Color.BLUE);

with:

g2d.setColor(Color.GREEN);

Exercise 2: Move the player

Modify the rectangle position:

g2d.fillRect(300, 200, 50, 50);

Observe how the square appears at a different location.

Exercise 3: Change the player size

Try drawing a larger rectangle:

g2d.fillRect(100, 100, 100, 100);

These simple exercises introduce coordinates, colors, and object dimensions, which are fundamental concepts in 2D game programming.

Summary

In this tutorial, we learned how to create our first 2D game window using Java Swing.

We covered:

  • The basic concepts of 2D game programming.
  • Why Java Swing is useful for learning game development.
  • How to create a game window using JFrame.
  • How to create a drawing area using JPanel.
  • How to draw a rectangle using Graphics2D.
  • Why Swing applications use the Event Dispatch Thread.

In the next tutorial, How do I create a game window using Java Swing?, we will explore game window configuration in greater detail and separate our main window from the drawing panel.

Maven Dependencies

Java Swing and Java 2D are included in the standard JDK through the java.desktop module, so no external dependencies are required.

We only need to configure Maven to compile our project with Java 25.

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 artifacts: None for Swing or Java 2D.

The Maven Compiler Plugin is configured as a build plugin, not an application dependency.

Java API references: