How do I implement the Prototype pattern in Java?

Suppose an application creates monthly sales reports with the same initial sections. A configured report can serve as a template. Each month, the application copies it, changes the title, and adds the sections needed for that month.

Prototype is a Gang of Four creational pattern that creates objects by copying an existing instance. The prototype carries the configuration from which new objects are produced. A client can request a copy through an interface while the concrete class implements its copying rules. GoF pattern catalog

This article completes our creational patterns series following Factory Method, Abstract Factory, and Builder. The series began with the existing Singleton example. Singleton pattern

A complete example

Save the following code as PrototypeExample.java. It uses standard Java APIs available in Java 8 and later.

package org.kodejava.pattern.prototype;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class PrototypeExample {
    interface Report {
        Report copy();
        void setTitle(String title);
        void addSection(String section);
    }

    static final class SalesReport implements Report {
        private String title;
        private final List<String> sections;

        SalesReport(String title, List<String> sections) {
            this.title = Objects.requireNonNull(title);
            this.sections = new ArrayList<>(sections);
        }

        private SalesReport(SalesReport original) {
            this(original.title, original.sections);
        }

        @Override
        public SalesReport copy() {
            return new SalesReport(this);
        }

        @Override
        public void setTitle(String title) {
            this.title = Objects.requireNonNull(title);
        }

        @Override
        public void addSection(String section) {
            sections.add(Objects.requireNonNull(section));
        }

        @Override
        public String toString() {
            return title + " " + sections;
        }
    }

    static Report customize(Report prototype) {
        Report report = prototype.copy();
        report.setTitle("November sales");
        report.addSection("Regional totals");
        return report;
    }

    public static void main(String[] args) {
        Report template = new SalesReport("Sales template",
                Arrays.asList("Summary", "Revenue"));
        Report november = customize(template);

        System.out.println("Template: " + template);
        System.out.println("Copy: " + november);
        System.out.println("Same instance: " + (template == november));

        november.addSection("Forecast");
        System.out.println("Template after edit: " + template);
        System.out.println("Copy after edit: " + november);
    }
}

Compile and run the example from the directory containing the source file.

javac -d out PrototypeExample.java
java -cp out org.kodejava.pattern.prototype.PrototypeExample

The program prints the original template and customized copy, then edits the copy again.

Template: Sales template [Summary, Revenue]
Copy: November sales [Summary, Revenue, Regional totals]
Same instance: false
Template after edit: Sales template [Summary, Revenue]
Copy after edit: November sales [Summary, Revenue, Regional totals, Forecast]

How copying works

GoF role Example Responsibility
Prototype Report Declares the copying operation used by the client.
Concrete prototype SalesReport Copies its title and sections according to its own rules.
Client customize() Obtains a copy through the interface and customizes it.
Configured prototype instance template in main() Supplies the initial report state.

The application creates the template once. The customize() method receives it through the Report interface and calls copy(). The concrete prototype returns a new SalesReport using a private copy constructor. Another report implementation could supply its own copying behavior through the same interface.

The false identity comparison shows that the template and copy are distinct report instances. Their section lists are also separate. The constructor creates a new ArrayList, so adding Regional totals or Forecast to the copy leaves the template’s sections intact.

The list elements are strings, which are immutable, so both lists can safely refer to the same section strings. If sections become mutable objects with their own fields, copying the list will still share those elements. The copy implementation must then decide which elements to duplicate and which references to share.

Choosing a copy policy

A useful copy contract states what the new object inherits and what becomes independent. In this example, the copy starts with the same title and section values, then owns its own mutable section list. A business object might also need a new identifier or a cleared creation timestamp.

Java provides Object.clone(), whose default behavior copies field values and shares referenced objects. This is a shallow copy. Our example exposes an explicit copy() method and constructs its result with the required list ownership. The Prototype pattern’s copying contract can be implemented this way. Object.clone() documentation

More elaborate object graphs require additional decisions. Shared subobjects, cycles, open resources, and external identities all affect what a valid copy means. Keep those decisions in the concrete prototype and document them for callers.

When should I use Prototype?

Prototype fits applications that repeatedly create objects from configured templates, particularly when client code works with multiple concrete types through a shared interface. A registry of named templates can let callers choose the starting configuration at runtime.

Copying also has a maintenance cost. When fields are added, review the copy operation so the new state receives the intended treatment. Copying large mutable graphs can consume substantial memory and time. Measure the actual construction and copying costs before choosing Prototype for performance.

For a small object with straightforward initialization, a constructor or factory can be sufficient. Prototype becomes useful when an existing instance provides the state needed to create another object.

Next, we begin structural patterns with Adapter.

How do I set up Project Lombok in a Java 25 Maven project?

Project Lombok generates common Java code during compilation. In this example, it generates getters and a setter for a Book class. You can call those methods from Java as soon as the project compiles.

Configure Maven

Use JDK 25 and Maven 3.9.x. Run mvn -v and check that Maven reports Java 25. Then create this pom.xml in the project root.

<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.kodejava</groupId>
    <artifactId>lombok-getting-started</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <lombok.version>1.18.44</lombok.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The provided dependency makes Lombok’s annotations available at compile time. The annotationProcessorPaths entry tells the compiler where to load Lombok’s annotation processor. With JDK 25, the dependency declaration alone does not activate annotation processing. The compiled example runs without the Lombok JAR.

Generate your first getter and setter

Create src/main/java/org/kodejava/lombok/Book.java.

package org.kodejava.lombok;

import lombok.Getter;
import lombok.Setter;

public class Book {
    @Getter
    private final String isbn;

    @Getter
    @Setter
    private String title;

    public Book(String isbn, String title) {
        this.isbn = isbn;
        this.title = title;
    }
}

@Getter generates getIsbn() and getTitle(). @Setter generates setTitle(String title). The ISBN is set in the constructor and remains fixed for the lifetime of the object.

Create src/main/java/org/kodejava/lombok/Main.java and call the generated methods.

package org.kodejava.lombok;

public class Main {
    public static void main(String[] args) {
        Book book = new Book("9780134685991", "Effective Java");
        System.out.println(book.getIsbn());
        System.out.println(book.getTitle());

        book.setTitle("Effective Java, Third Edition");
        System.out.println(book.getTitle());
    }
}

Compile and run

Run these commands from the directory containing pom.xml.

mvn clean compile
java -cp target/classes org.kodejava.lombok.Main

The program prints the ISBN, the original title, and the updated title.

9780134685991
Effective Java
Effective Java, Third Edition

If Maven compiles the example and your IDE still marks getTitle() as unresolved, check the IDE’s Lombok support and annotation processing settings, then reload the Maven project.

References

Maven artifact

The example uses org.projectlombok:lombok:1.18.44. Keep the dependency and annotation processor on the same Lombok version.

How do I create a window using JFrame in Java?

Use JFrame to create a Swing window with a title bar and an area for components. In this example, you will open a window with a centered welcome message.

Source code

Save the following code as JFrameExample.java:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

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

    private void showWindow() {
        JFrame frame = new JFrame("Hello, Swing!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel message = new JLabel(
                "Welcome to Swing", SwingConstants.CENTER);
        frame.add(message);

        frame.setSize(400, 240);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of a window titled Hello, Swing! with a centered Welcome to Swing message

This illustration shows the layout. The title bar and window controls may look different on your operating system.

Explanation

new JFrame("Hello, Swing!") creates the window and sets its title. EXIT_ON_CLOSE tells Java to exit the application when you close this window.

The JLabel displays Welcome to Swing. SwingConstants.CENTER centers the text horizontally, and frame.add(message) places the label inside the window.

setSize(400, 240) sets the size of the entire window, including its border and title bar. Call setLocationRelativeTo(null) after setting the size to center the window on the screen. Finally, setVisible(true) displays it.

The main() method uses SwingUtilities.invokeLater(this::showWindow) to schedule window creation on Swing’s event dispatch thread. This is the thread Swing uses to handle events and update the interface.

Run the example

Compile and run the file:

javac JFrameExample.java
java JFrameExample

A window titled Hello, Swing! opens with the welcome message in the center. Close the window to end the program.

How do I send and receive JMS messages with Spring Boot?

When an application creates an order, it may also need to arrange shipping or send a confirmation email. A queue lets the application hand off that work. The application sends a message containing the order ID, and a consumer processes it asynchronously.

In this first article, you’ll send a message to the orders.created queue with JmsTemplate and receive it with @JmsListener. The example uses Java 25, Maven, Spring Boot 4.1.2, and Apache ActiveMQ Artemis.

What is JMS?

Java Message Service (JMS), now called Jakarta Messaging, defines a standard Java API for sending and receiving messages. Modern Spring applications use the jakarta.jms package. In this example, ActiveMQ Artemis is the message broker that manages the queue and delivers messages.

Component Role
Producer Sends a message announcing that order ORD-1001 was created.
Broker Accepts the message and delivers it to a consumer.
Queue Holds messages for delivery. If multiple consumers listen to the same queue, each delivery goes to one consumer, allowing them to share the work.
Consumer Receives the message from the queue and logs its contents.

Spring Boot configures the connection to Artemis and sets up the Spring JMS infrastructure. For this tutorial, Artemis runs as an embedded broker in the same Java process as the producer and consumer. You only need JDK 25 and Maven. Broker persistence is disabled, so any messages still in the queue are lost when the broker stops.

1. Create a Maven project

Save this configuration as pom.xml in the project directory.

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.2</version>
        <relativePath/>
    </parent>

    <groupId>org.kodejava</groupId>
    <artifactId>spring-jms-week-01</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <java.version>25</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-artemis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>artemis-jakarta-server</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2. Configure the broker and queue

Create src/main/resources/application.properties.

spring.artemis.mode=embedded
spring.artemis.embedded.persistent=false
spring.artemis.embedded.queues=orders.created

The last property tells Spring Boot to create the orders.created queue when the embedded broker starts.

3. Send a message at startup

Create src/main/java/org/kodejava/jms/OrderMessagingApplication.java.

package org.kodejava.jms;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.core.JmsTemplate;

@SpringBootApplication
public class OrderMessagingApplication {
    static final String ORDERS_CREATED = "orders.created";

    public static void main(String[] args) {
        SpringApplication.run(OrderMessagingApplication.class, args);
    }

    @Bean
    CommandLineRunner sendOrderCreated(JmsTemplate jmsTemplate) {
        return args -> jmsTemplate.convertAndSend(ORDERS_CREATED, "ORD-1001");
    }
}

The CommandLineRunner sends one message each time the application starts. The first argument to convertAndSend() is the destination name, and the second is the payload. The default message converter turns the Java String into a JMS TextMessage.

4. Receive the message from the queue

Create src/main/java/org/kodejava/jms/OrderCreatedListener.java.

package org.kodejava.jms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class OrderCreatedListener {
    private static final Logger log =
            LoggerFactory.getLogger(OrderCreatedListener.class);

    @JmsListener(destination = OrderMessagingApplication.ORDERS_CREATED)
    public void onOrderCreated(String orderId) {
        log.info("Order created - orderId={}", orderId);
    }
}

Spring registers the method annotated with @JmsListener with a listener container. When Artemis delivers a message from the queue, Spring extracts the text from the TextMessage and passes it to the method as the orderId argument. The listener processes the message asynchronously.

5. Run the application and check the output

Run this command from the directory containing pom.xml.

mvn spring-boot:run

Look for this message in the application log.

Order created - orderId=ORD-1001

The listener writes this log entry after receiving the message, so it confirms that the message traveled through the broker and reached the consumer. Press Ctrl+C to stop the application.

In the next article, we’ll run Artemis in Docker and connect to it over the network. We’ll reuse the producer, the consumer, and the orders.created queue name.

References

Maven Artifacts

Artifact Purpose
org.springframework.boot:spring-boot-starter-parent:4.1.2 Provides the parent POM and manages dependency versions.
org.springframework.boot:spring-boot-starter-artemis Adds Spring JMS integration and the Artemis client.
org.apache.activemq:artemis-jakarta-server Provides the embedded Artemis broker.
org.springframework.boot:spring-boot-maven-plugin Runs the application with mvn spring-boot:run.

How do I draw 2D shapes using Graphics2D?

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