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

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





