How do I split a string and keep its delimiters in Java 21?

Sometimes you need both the pieces of a string and the separators between them. For example, a text-processing tool might need to preserve commas and semicolons while inspecting individual values.

Java 21 provides String.splitWithDelimiters() for this task.

1. Choose the separators

Our input is:

red,green;blue;

The regular expression [,;] matches either a comma or a semicolon.

Unlike split(), splitWithDelimiters() includes matched separators as elements in the returned array. See the Java 21 String API.

2. Keep the pieces and reconstruct the text

Save the following as KeepDelimitersExample.java:

import java.util.Arrays;

public class KeepDelimitersExample {
    public static void main(String[] args) {
        String text = "red,green;blue;";
        String regex = "[,;]";

        System.out.println(
                "split: " + Arrays.toString(text.split(regex, -1)));

        String[] parts = text.splitWithDelimiters(regex, -1);
        System.out.println("keep: " + Arrays.toString(parts));

        System.out.println("Rebuilt: " + String.join("", parts));

        System.out.println("limit 2: " + Arrays.toString(
                text.splitWithDelimiters(regex, 2)));

        System.out.println("limit 0: " + Arrays.toString(
                text.splitWithDelimiters(regex, 0)));
    }
}

The program compares ordinary splitting with delimiter-preserving splitting. It then joins the preserved pieces without adding any extra characters.

3. Compile and run

From the directory containing the file:

javac --release 21 KeepDelimitersExample.java
java KeepDelimitersExample

Output:

split: [red, green, blue, ]
keep: [red, ,, green, ;, blue, ;, ]
Rebuilt: red,green;blue;
limit 2: [red, ,, green;blue;]
limit 0: [red, ,, green, ;, blue, ;]

The two adjacent commas in the keep line can look confusing: one is a delimiter element, while the other is punctuation added by Arrays.toString().

4. Understand the limit

The second argument controls splitting:

Limit Behavior
Negative Processes all matches and preserves trailing empty strings.
Zero Processes all matches but removes trailing empty strings.
Positive Processes at most limit - 1 matches, leaving the remaining input together.

With limit 2, only the first comma is processed. The result therefore contains three elements: "red", ",", and "green;blue;".

A positive limit does not directly cap the array length at that number, because delimiter elements are included. These rules are specified in the method documentation.

Best practices

  • Use this method when separators carry information you need later.
  • Test leading, consecutive, and trailing separators with your chosen pattern.
  • Remember that the first argument is a regular expression. Use Pattern.quote() when a user-supplied separator should be treated literally.
  • Use a CSV parser for quoted CSV fields; splitting on commas alone does not implement CSV rules.

Summary

splitWithDelimiters() lets you inspect string segments while preserving their separators. Choose the limit deliberately, especially when trailing empty values matter.

How do I display a message dialog in Java Swing?

Use JOptionPane.showMessageDialog() to display a short message with an OK button. This example opens an information dialog without creating a separate JFrame.

Source code

Save the following code as MessageDialogExample.java:

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class MessageDialogExample {
    void main() {
        SwingUtilities.invokeLater(this::showMessage);
    }

    private void showMessage() {
        JOptionPane.showMessageDialog(
                null,
                "Hello from Swing!",
                "Message",
                JOptionPane.INFORMATION_MESSAGE);
    }
}

What the dialog looks like

Illustration of a dialog titled Message, with the text Hello from Swing! and an OK button

The icon and window styling depend on your system and Swing look and feel.

Explanation

The showMessageDialog() call uses four arguments:

Argument Purpose
null Shows the dialog without positioning it relative to an existing component
"Hello from Swing!" Sets the message shown inside the dialog
"Message" Sets the title shown in the title bar
JOptionPane.INFORMATION_MESSAGE Selects the information message type, which usually displays an information icon

If your application already has a window, pass its JFrame instead of null so Swing can position the dialog relative to that window.

SwingUtilities.invokeLater() schedules showMessage() on Swing’s event dispatch thread. The dialog is modal, so the call to showMessageDialog() returns after the user dismisses the dialog. It returns no value. If you need to ask a question and read the user’s choice, use showConfirmDialog().

Run the example

javac MessageDialogExample.java
java MessageDialogExample

A dialog titled Message displays Hello from Swing!. Click OK to dismiss it.

How do I animate merging metaballs in Java Swing?

You can create blobs that appear to merge by adding together scalar fields and coloring pixels according to the total. In this SwingLoops example, five moving centers produce luminous shapes that join and separate without collision detection or a fluid engine.

Metaball Fusion
Metaball Fusion

Source code

Save this code as MetaballFusion.java:

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

public class MetaballFusion extends JPanel {
    private static final int W = 180, H = 320, COUNT = 5;
    private static final double CYCLE = 12.0;
    private final BufferedImage image =
            new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
    private final int[] pixels =
            ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
    private final double[] cx = new double[COUNT], cy = new double[COUNT];
    private final Timer timer = new Timer(33, _ -> repaint());
    private long start;

    public MetaballFusion() {
        setPreferredSize(new Dimension(450, 800));
        setBackground(new Color(6, 11, 24));
    }

    @Override public void addNotify() {
        super.addNotify();
        start = System.nanoTime();
        timer.start();
    }

    @Override public void removeNotify() {
        timer.stop();
        super.removeNotify();
    }

    private static double smooth(double a, double b, double x) {
        double u = Math.max(0, Math.min(1, (x - a) / (b - a)));
        return u * u * (3 - 2 * u);
    }

    private void render(double seconds) {
        double phase = 2 * Math.PI * (seconds % CYCLE) / CYCLE;
        for (int i = 0; i < COUNT; i++) {
            double offset = i * 2 * Math.PI / COUNT;
            cx[i] = W / 2.0 + 48 * Math.cos(phase + offset);
            cy[i] = H / 2.0 + 70 * Math.sin(2 * phase + offset);
        }

        for (int y = 0; y < H; y++) {
            for (int x = 0; x < W; x++) {
                double field = 0;
                for (int i = 0; i < COUNT; i++) {
                    double dx = x - cx[i], dy = y - cy[i];
                    field += 196.0 / (dx * dx + dy * dy + 1);
                }
                double fill = smooth(0.94, 1.06, field);
                double edge = Math.exp(-Math.pow((field - 1) / 0.12, 2));
                double inside = fill * (0.58 + 0.25 *
                        Math.sin(x * 0.035 + y * 0.02 + phase));
                int red = (int) Math.min(255, 6 + 48 * inside + 116 * edge);
                int green = (int) Math.min(255, 11 + 192 * inside + 150 * edge);
                int blue = (int) Math.min(255, 24 + 210 * inside + 170 * edge);
                pixels[y * W + x] = (red << 16) | (green << 8) | blue;
            }
        }
    }

    @Override protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        render((System.nanoTime() - start) / 1e9);
        Graphics2D g = (Graphics2D) graphics.create();
        try {
            double scale = Math.min(getWidth() / (double) W,
                                    getHeight() / (double) H);
            g.translate((getWidth() - W * scale) / 2,
                        (getHeight() - H * scale) / 2);
            g.scale(scale, scale);
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                               RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(image, 0, 0, null);
        } finally {
            g.dispose();
        }
    }

    static void main() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingLoops - Metaball Fusion");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new MetaballFusion());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Run the example

Install a JDK and use a desktop environment that supports Swing. In the directory containing the source file, run:

javac MetaballFusion.java
java MetaballFusion

Compilation was verified with JDK 25. Visual playback has not yet been verified. Close the window to exit.

Build a scalar field

At each pixel, the program calculates the distance from each moving center and adds a contribution:

field += 196.0 / (dx * dx + dy * dy + 1);

A nearby center contributes a large value; a distant center contributes less. The added one prevents division by zero at a center.

The visible surface is defined by a field value near one. For an isolated center, that value would occur at a distance of approximately 14 pixels. The combined fields of neighboring centers enlarge and deform that boundary.

Why do the blobs merge?

Suppose a pixel between two centers receives 0.6 from each. Neither contribution reaches the threshold on its own, but their sum is 1.2. That pixel belongs to the filled region.

As the centers approach, more pixels between them cross the threshold and form a connecting neck. When they separate, those pixels fall below the threshold again. The program does not need a special instruction to join or split shapes.

Color the boundary

A smoothstep function changes the fill from zero to one over the interval 0.94–1.06:

double fill = smooth(0.94, 1.06, field);

A narrow Gaussian-shaped function adds a bright edge around the threshold:

double edge = Math.exp(-Math.pow((field - 1) / 0.12, 2));

Its value is greatest when the field equals one and decreases on either side. This is a glow in field-value space rather than a constant-width blur in screen pixels.

The interior also uses a gentle sinusoidal color variation. The final RGB channels are clamped before being packed into an integer pixel.

Move the centers

Each center follows a sinusoidal path with a different phase offset:

cx[i] = W / 2.0 + 48 * Math.cos(phase + offset);
cy[i] = H / 2.0 + 70 * Math.sin(2 * phase + offset);

The vertical motion completes two oscillations for each horizontal oscillation. After 12 seconds, both coordinates and the interior coloring return to their starting states.

Render with Swing

The calculation runs at 180 × 320 pixels to limit per-frame work. A BufferedImage backed by an integer array lets the program write colors directly. Java 2D scales the image with bilinear interpolation for display.

A Swing timer requests repaints approximately every 33 milliseconds. Motion depends on elapsed time, not the number of frames. The interface and painting run on the event-dispatch thread. More fields or a higher internal resolution increase painting work and may reduce responsiveness.

Customize the effect

Try increasing the strength from 196 to 256. Because the boundary depends on the sum, this makes the blobs larger and encourages merging. Then increase the horizontal orbit amplitude from 48 to 60 to pull them farther apart.

This example is an artistic field visualization, not a simulation of liquid pressure or surface tension. The complete source is free to copy and run.

Explore the SwingLoops repository for more Java animation examples.

How do I read text from a JTextField in Java Swing?

Call getText() on a JTextField to read what the user has typed. In this example, the user enters a name and clicks Say hello or presses Enter to display a greeting.

Source code

Save the following code as TextFieldExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class TextFieldExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JTextField nameField = new JTextField(14);
        JLabel nameLabel = new JLabel("Name:");
        nameLabel.setLabelFor(nameField);

        JButton greetButton = new JButton("Say hello");
        JLabel greeting = new JLabel(
                "Enter your name.", SwingConstants.CENTER);

        greetButton.addActionListener(event ->
                updateGreeting(nameField, greeting));
        nameField.addActionListener(event ->
                updateGreeting(nameField, greeting));

        JPanel form = new JPanel();
        form.add(nameLabel);
        form.add(nameField);
        form.add(greetButton);

        JPanel content = new JPanel(new BorderLayout(0, 12));
        content.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
        content.add(form, BorderLayout.PAGE_START);
        content.add(greeting, BorderLayout.CENTER);

        JFrame frame = new JFrame("Text Field Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void updateGreeting(JTextField nameField, JLabel greeting) {
        String name = nameField.getText().strip();

        if (name.isEmpty()) {
            greeting.setText("Please enter your name.");
        } else {
            greeting.setText("Hello, " + name + "!");
        }
    }
}

What the window looks like

Illustration of the Swing window showing Rosa in the text field and Hello, Rosa! below it

Explanation

new JTextField(14) creates a single-line text field. The number 14 helps Swing calculate its preferred width. The user can still type more than 14 characters.

The updateGreeting() method reads the field when the user submits the name:

String name = nameField.getText().strip();

getText() returns the current text. strip() removes whitespace from both ends of the returned string without changing what appears in the field. If the result is empty, the label asks for a name. Otherwise, it displays a greeting.

Both the button and the text field have an action listener that calls updateGreeting(). The button listener runs when the button is activated. The text field listener runs when the user presses Enter while the field has focus. Both listeners run on Swing’s event dispatch thread and can update the label directly.

Run the example

javac TextFieldExample.java
java TextFieldExample

Type Rosa and click Say hello. The label displays Hello, Rosa!. Clear the field and press Enter to see Please enter your name.

How do I understand coordinates in a 2D game?

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