How do I create a game window using Java Swing?

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

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

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

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

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

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

1. Understanding the game window

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

JFrame — The game window

JFrame represents the main window of our desktop application.

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

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

JPanel — The drawing area

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

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

Our application will have three classes:

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

This separation makes our code easier to understand and extend.

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

2. Creating the Maven project

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

We will organize the project using the following structure:

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

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

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

3. Creating the GamePanel class

Let’s start with the drawing area.

Create a file named GamePanel.java:

package org.kodejava.game;

import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

public class GamePanel extends JPanel {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Understanding setPreferredSize()

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

setPreferredSize(new Dimension(
        GAME_WIDTH, GAME_HEIGHT));

We use an 800 × 600 pixel drawing area.

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

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

Understanding paintComponent()

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

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

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

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

The Graphics object represents the drawing context supplied by Swing.

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

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

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

Why do we call super.paintComponent()?

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

super.paintComponent(g);

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

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

What is double buffering?

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

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

The completed image is then displayed.

In our example, we call:

setDoubleBuffered(true);

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

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

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

4. Creating the GameWindow class

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

Create GameWindow.java:

package org.kodejava.game;

import javax.swing.JFrame;

public class GameWindow extends JFrame {

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

        setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);

        setContentPane(new GamePanel());

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

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

Let’s examine its configuration.

Setting the window title

setTitle("KodeJava 2D Game");

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

Configuring the close operation

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

For our simple standalone game, this behavior is appropriate.

Adding the GamePanel

setContentPane(new GamePanel());

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

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

Its responsibility is to manage the window.

Using pack()

pack();

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

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

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

Centering the game window

setLocationRelativeTo(null);

This positions the window in the center of the screen.

Preventing window resizing

setResizable(false);

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

This makes it easier to understand coordinates and object positions.

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

5. Creating the Game class

Finally, create the application’s entry point.

Create Game.java:

package org.kodejava.game;

import javax.swing.SwingUtilities;

public class Game {

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

This is now a very small class.

Its only responsibility is to start our application.

Why use SwingUtilities.invokeLater()?

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

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

SwingUtilities.invokeLater(GameWindow::new);

This is equivalent to:

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

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

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

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

6. Running the game

We now have three Java classes:

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

Compile the project:

mvn clean compile

Then run the application from your IDE.

You can also execute it from the command line:

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

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

Game Window

Inside the window, you should see:

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

The blue square represents our player.

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

7. Understanding the rendering coordinates

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

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

For example:

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

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

Its width and height are both 50 pixels.

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

int playerSize = 50;

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

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

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

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

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

We will explore coordinates in more detail in Week 04.

8. Why separate GameWindow and GamePanel?

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

The main reason is separation of responsibilities.

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

This separation becomes more valuable as we develop larger games.

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

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

Each class will have a specific responsibility.

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

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

9. Try it yourself

Before moving to the next tutorial, try these exercises.

Exercise 1 — Change the game resolution

Modify the dimensions in GamePanel:

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

Run the application again.

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

Exercise 2 — Change the background color

Replace:

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

with:

setBackground(Color.DARK_GRAY);

Exercise 3 — Draw another object

Add the following code inside drawPlayer():

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

Now the game displays both a square and a circle.

Exercise 4 — Allow window resizing

Change:

setResizable(false);

to:

setResizable(true);

Try resizing the window.

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

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

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

10. Summary

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

We learned how to:

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

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

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

Maven Dependencies

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

We do not need any external libraries for this tutorial.

Here is the complete pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
             http://maven.apache.org/POM/4.0.0
             https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.kodejava</groupId>
    <artifactId>java-2d-game</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
            </plugin>
        </plugins>
    </build>
</project>

Required Maven dependencies: None.

Build plugin: org.apache.maven.plugins:maven-compiler-plugin:3.14.1

References

How do I convert a list of strings to uppercase using a stream in Java?

You can use the Stream API’s map() method to transform each string in a list. Call toUpperCase() inside the mapping function, then collect the results with toList().

In this example, you will convert programming language names to uppercase without changing the original list.

Source code

Save the following code as UppercaseListExample.java:

import java.util.List;
import java.util.Locale;

public class UppercaseListExample {
    void main() {
        List<String> languages = List.of(
                "Java", "Python", "Kotlin");

        List<String> uppercaseLanguages = languages.stream()
                .map(language -> language.toUpperCase(Locale.ROOT))
                .toList();

        IO.println("Original list: " + languages);
        IO.println("Uppercase list: " + uppercaseLanguages);
    }
}

Explanation

The original list contains three strings with mixed capitalization:

List<String> languages = List.of(
        "Java", "Python", "Kotlin");

The following pipeline transforms each element and collects the results:

List<String> uppercaseLanguages = languages.stream()
        .map(language -> language.toUpperCase(Locale.ROOT))
        .toList();

Each step has a purpose:

Step Purpose
stream() Creates a sequential stream of the list’s elements
map(...) Converts each string to uppercase
toList() Collects the converted strings into an unmodifiable list

Transforming each element

The map() method applies a function to each element:

language -> language.toUpperCase(Locale.ROOT)

For example, "Java" becomes "JAVA".

Unlike filter(), which selects matching elements, map() transforms them. This pipeline produces one result for each input element.

Choosing a locale

Uppercase conversion can depend on language rules. Calling toUpperCase() without an argument uses the system’s default locale.

This example passes Locale.ROOT explicitly:

language.toUpperCase(Locale.ROOT)

It uses language-neutral casing rules, making the conversion independent of the system’s default locale. For text intended for a specific language, use the appropriate locale instead.

Keeping the original values

Strings are immutable. Calling toUpperCase() returns an uppercase result without modifying the original string.

The stream pipeline also leaves the original list unchanged. The result list preserves the original element order.

The list returned by toList() is unmodifiable. Calling add(), remove(), or set() on it would throw an UnsupportedOperationException.

Run the example

Compile and run the file:

javac UppercaseListExample.java
java UppercaseListExample

Output

Original list: [Java, Python, Kotlin]
Uppercase list: [JAVA, PYTHON, KOTLIN]

Use map() when you want to transform every element, such as converting text, extracting an object’s field, or calculating a new value.

How Do I Use Kotlin to Model Tasks in an Android App?

In article 1, you created Task Notes and its empty screen. Now you will describe the data behind a task using Kotlin. You will create a Task model, prepare sample tasks, and display one task on the existing screen. The next article will turn those samples into a scrolling list.

Practical goal

By the end, you will be able to declare typed properties, use default and named arguments, create a read-only list, and produce an updated task with copy().

Continue with the same Android Studio project. This example keeps the package org.kodejava.tasknotes, the generated TaskNotesTheme, and minimum SDK API 24 from article 1. If you used your own package, adjust the package declarations and imports below.

1. Create the Task model

Create the model package below org.kodejava.tasknotes. Add this file:

File: app/src/main/java/org/kodejava/tasknotes/model/Task.kt

package org.kodejava.tasknotes.model

data class Task(
    val id: Long,
    val title: String,
    val isCompleted: Boolean = false
)

A model describes information that the app works with. Here, each task has three properties:

Property Type Purpose
id Long Identifies the task even when its title changes
title String Holds the text shown to the user
isCompleted Boolean Records whether the task is done

The colon introduces a type. Boolean has two values: true and false. The default value means a new task starts incomplete unless you supply another value.

String does not accept null. It still accepts empty text such as ""; non-null types do not replace input validation. You will add form validation in a later article.

The data keyword asks Kotlin to generate useful operations such as equality checks, readable text output, and copying. Keep the properties in the primary constructor so those generated operations include them. See the official data class documentation.

2. Understand val and named arguments

This is an example of constructing a task; you do not need to add it to a file yet:

val task = Task(id = 1L, title = "Learn Kotlin basics")

val declares a reference that cannot be reassigned. The model also uses val properties, so you cannot assign a new title directly to an existing task.

1L is a Long literal. Named arguments such as title = ... make constructor calls easier to read. Since we omitted isCompleted, its value is false.

Kotlin also has var for variables that can be reassigned. We use val here to make changes explicit through new objects.

3. Prepare reusable sample data

Create a data package and add the following file:

File: app/src/main/java/org/kodejava/tasknotes/data/SampleTasks.kt

package org.kodejava.tasknotes.data

import org.kodejava.tasknotes.model.Task

fun sampleTasks(): List<Task> = listOf(
    Task(id = 1L, title = "Learn Kotlin basics"),
    Task(id = 2L, title = "Create the Task model", isCompleted = true),
    Task(id = 3L, title = "Build the task list")
)

fun declares a function. This function takes no arguments and returns a List<Task>, meaning a list whose elements are tasks. The = introduces a function with a single expression as its body.

listOf() creates the sample list. List exposes read-only operations: callers can inspect its elements but cannot call add() through that interface. A read-only interface is not a general guarantee that an underlying collection can never change. Our sample contains tasks with read-only properties and exposes no mutation operations.

The sample IDs are distinct and remain the same each time this function is called. They are manually assigned tutorial values; the function does not generate IDs for future user-created tasks. A title is not an ID because two tasks may have the same title.

Reference: Kotlin collections overview.

4. Display a task on the existing screen

In MainActivity.kt, add this import alongside the existing imports:

import org.kodejava.tasknotes.data.sampleTasks

Replace only the existing TaskNotesScreen() function with the code below. Keep MainActivity, its Scaffold and innerPadding, all existing Compose imports, and TaskNotesScreenPreview() from article 1.

File: app/src/main/java/org/kodejava/tasknotes/MainActivity.kt

@Composable
private fun TaskNotesScreen(modifier: Modifier = Modifier) {
    val tasks = sampleTasks()
    val task = tasks.first()
    val status = if (task.isCompleted) "Completed" else "Not completed"

    Column(
        modifier = modifier.fillMaxSize().padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium
        )
        Text(
            text = task.title,
            style = MaterialTheme.typography.bodyLarge
        )
        Text(text = "Status: $status")
        Text(text = "Sample tasks: ${tasks.size}")
    }
}

Kotlin infers the types of tasks, task, and status from their values. first() reads the first element. It is safe here because our sample function always returns three tasks; it would throw an exception for an empty list.

An if expression produces the status text. String templates insert values into text: $status inserts a variable, while ${tasks.size} evaluates an expression.

This screen only reads fixed sample data. Calling sampleTasks() during composition is acceptable for this tiny example; it is not a strategy for loading database data. Interactive state and its ownership come later in the series.

5. Create an updated task with copy()

To try a completed version, replace this line inside TaskNotesScreen():

val task = tasks.first()

with:

val original = tasks.first()
val task = original.copy(isCompleted = true)

The copied task keeps the original ID and title but has a new completion value. The original task and the task stored in the sample list remain incomplete. Copying an object does not replace an element in a list.

copy() is shallow: nested objects would still be shared. This model contains only a number, text, and a Boolean, so no mutable nested collection is involved.

After checking the result, restore val task = tasks.first() so your project matches the starting point for article 3.

6. Verify the result

  1. Sync the project if Android Studio requests it, then run the app on the emulator or phone used in article 1.
  2. Check that the screen shows the following text:
Task Notes
Learn Kotlin basics
Status: Not completed
Sample tasks: 3
  1. Refresh the existing Compose preview. It should show the same sample content.
  2. Try the copy() change from step 5. The status should become Completed, with the same title and sample count.
  3. Restore the original line and run again.

If Task or sampleTasks is unresolved, check the file package declarations and imports. If the compiler reports a type mismatch for an ID, use a Long literal such as 1L. If the preview cannot load, resolve build errors before refreshing it.

These are verification steps for your project. This draft’s Android build and device behavior have not been executed in an Android SDK environment.

Practice

  • Add a fourth sample task with ID 4L. Verify that the count becomes 4.
  • Display tasks[1] instead of the first task. The second task should show Completed. List indexes start at zero.
  • Use copy(title = "Review Kotlin basics") on the first task and observe that the original sample title stays unchanged.

Restore the three original samples and tasks.first() before continuing to the next article.

Gradle dependencies and compatibility

No additional Gradle dependencies are required. The model and sample function use the Kotlin standard library supplied by the existing Kotlin Android project. The screen reuses the Compose dependencies configured in article 1.

Keep the existing plugin and dependency versions in build.gradle.kts, app/build.gradle.kts, and gradle/libs.versions.toml if present. This lesson introduces no version-specific library API and does not require a Kotlin, Android Gradle Plugin, or Compose upgrade. Official Compose setup guidance remains the reference for project configuration.

Next in the series

In article 3, How Do I Display Tasks in a LazyColumn with Jetpack Compose?, you will reuse Task and sampleTasks() to render the task list.

How do I filter a list using a stream in Java?

You can use the Stream API’s filter() method to select elements that match a condition.

In this example, you will select numbers greater than or equal to 20 from a list and collect them into a new list.

Source code

Save the following code as FilterListExample.java:

import java.util.List;

public class FilterListExample {
    void main() {
        List<Integer> numbers = List.of(5, 20, 12, 35, 8, 40);

        List<Integer> filteredNumbers = numbers.stream()
                .filter(number -> number >= 20)
                .toList();

        IO.println("Original list: " + numbers);
        IO.println("Filtered list: " + filteredNumbers);
    }
}

Explanation

The original list contains six integers:

List<Integer> numbers = List.of(5, 20, 12, 35, 8, 40);

The following pipeline selects the matching values and collects them:

List<Integer> filteredNumbers = numbers.stream()
        .filter(number -> number >= 20)
        .toList();

Each step has a purpose:

Step Purpose
stream() Creates a sequential stream of the list’s elements
filter(...) Keeps elements that match the condition
toList() Collects the selected elements into a list

Defining the condition

The filter() method accepts a predicate: a function that checks an element and returns true or false.

Here, the predicate is a lambda expression:

number -> number >= 20

When the result is true, the number remains in the stream. When it is false, the number is excluded.

For this input, the matching values are 20, 35, and 40.

Collecting the result

filter() is an intermediate operation. It describes the selection but does not process the elements until a terminal operation runs.

In this example, toList() is the terminal operation:

.toList()

It collects the matching elements into an unmodifiable list. Calling add() or remove() on that result would throw an UnsupportedOperationException.

The result preserves the original list’s encounter order. Filtering does not change the original list.

Run the example

Compile and run the file:

javac FilterListExample.java
java FilterListExample

Output

Original list: [5, 20, 12, 35, 8, 40]
Filtered list: [20, 35, 40]

Combining conditions

Use && to require multiple conditions. For example, this filter keeps numbers that are at least 20 and even:

.filter(number -> number >= 20 && number % 2 == 0)

With the same input, the resulting list is:

[20, 40]

If no elements match the condition, toList() returns an empty list.

How do I animate a fractal tree in Java Swing?

You can draw a fractal tree by creating a branch and recursively drawing two shorter branches at its endpoint. Repeating this rule produces an intricate tree from a small amount of code.

In this SwingLoops example, the branches grow over time, sway gently, and fade away before the next cycle. Everything is drawn with Java Swing and Java 2D.

Fractal Tree Bloom

Fractal Tree Bloom

Source code

Save the following code as FractalTreeBloom.java:

package org.kodejava.swing.animation;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Line2D;

public class FractalTreeBloom extends JPanel {
    private static final int WIDTH = 450;
    private static final int HEIGHT = 800;
    private static final int LEVELS = 9;
    private static final double CYCLE = 12.0;

    private final Timer timer = new Timer(16, _ -> repaint());
    private long startedAt;

    public FractalTreeBloom() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(new Color(7, 13, 25));
    }

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

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

    private static double clamp(double value) {
        return Math.max(0, Math.min(1, value));
    }

    private static double smooth(double value) {
        return value * value * (3 - 2 * value);
    }

    private void branch(Graphics2D g, double x, double y,
                        double angle, double length, int level,
                        double growth, double spread, float fade) {
        if (level >= LEVELS) {
            return;
        }

        double local = smooth(clamp(growth - level));
        if (local <= 0) {
            return;
        }

        double endX = x + length * local * Math.cos(angle);
        double endY = y + length * local * Math.sin(angle);

        Color color = Color.getHSBColor(
                0.48f - level * 0.025f, 0.65f, 1f);
        float width = Math.max(1f, 5f - level * 0.5f);
        Line2D line = new Line2D.Double(x, y, endX, endY);

        g.setColor(color);
        g.setComposite(AlphaComposite.SrcOver.derive(fade * 0.10f));
        g.setStroke(new BasicStroke(width + 7f,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g.draw(line);

        g.setComposite(AlphaComposite.SrcOver.derive(fade));
        g.setStroke(new BasicStroke(width,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g.draw(line);

        if (local >= 1) {
            branch(g, endX, endY, angle - spread, length * 0.70,
                    level + 1, growth, spread, fade);
            branch(g, endX, endY, angle + spread, length * 0.70,
                    level + 1, growth, spread, fade);
        }
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        Graphics2D g = (Graphics2D) graphics.create();

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

            double scale = Math.min(
                    getWidth() / (double) WIDTH,
                    getHeight() / (double) HEIGHT);
            g.translate((getWidth() - WIDTH * scale) / 2,
                    (getHeight() - HEIGHT * scale) / 2);
            g.scale(scale, scale);

            double seconds = (System.nanoTime() - startedAt) / 1e9;
            double t = seconds % CYCLE;
            double growth = Math.min(LEVELS, t * LEVELS / 7.5);
            double wind = Math.sin(2 * Math.PI * t / 6.0);
            double spread = Math.toRadians(25 + 3 * wind);
            float fade = (float) (1 - clamp((t - 10) / 2));

            branch(g, WIDTH / 2.0, 685,
                    -Math.PI / 2 + 0.025 * wind,
                    130, 0, growth, spread, fade);
        } finally {
            g.dispose();
        }
    }

    static void main() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingLoops - Fractal Tree Bloom");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new FractalTreeBloom());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Run the example

You need a JDK and a desktop environment that supports Swing. From the directory containing the file, run:

javac FractalTreeBloom.java
java FractalTreeBloom

The application opens a portrait window with a preferred drawing area of 450 × 800 pixels. Resizing preserves the drawing’s proportions. Close the window to exit.

Draw one branch

Each branch starts at (x, y) and extends in the direction given by angle. Sine and cosine convert its length and angle into an endpoint:

double endX = x + length * local * Math.cos(angle);
double endY = y + length * local * Math.sin(angle);

The local value controls how much of the branch is visible. Zero means no visible length; one means the branch has reached its full length.

The trunk starts at an angle of -Math.PI / 2. Swing’s vertical coordinates increase downward, so this angle points upward.

Repeat the rule with recursion

When a branch finishes growing, it creates two children at its endpoint:

branch(g, endX, endY, angle - spread, length * 0.70,
        level + 1, growth, spread, fade);
branch(g, endX, endY, angle + spread, length * 0.70,
        level + 1, growth, spread, fade);

The children turn in opposite directions and have 70% of their parent’s length. Each child follows the same rule.

The method stops when level reaches LEVELS. With nine levels, numbered zero through eight, a completed tree contains:

1 + 2 + 4 + ... + 256 = 511 branches

The stopping condition matters: without it, the recursive calls would continue until the program exhausted its stack.

Reveal the levels over time

The growth value increases from zero to nine over 7.5 seconds. Each branch subtracts its level to obtain its own progress:

double local = smooth(clamp(growth - level));

For example, when growth is 2.5, the trunk and level-one branches are complete. Level-two branches are halfway through their growth, and deeper levels are still hidden.

The smoothstep function eases the motion:

return value * value * (3 - 2 * value);

Its slope is zero at both ends, so a branch begins and finishes growing gently.

Add wind, color, and glow

A sine function changes the branching angle slightly over time. The same wind value also tilts the trunk. This creates a stylized sway; the code does not simulate forces or flexible wood.

The hue changes with branch level, giving the trunk and tips different colors. Each branch is drawn twice: a wide transparent stroke creates a halo, and a thinner bright stroke forms the visible branch.

Growth finishes at 7.5 seconds. The completed tree continues swaying, then fades from ten to twelve seconds. At the cycle boundary, growth returns to zero and the tree starts again.

Update the animation with Swing

A Swing timer requests repaints approximately every 16 milliseconds. Positions depend on elapsed time rather than frame counts, so delayed repaints do not change the intended cycle duration.

The interface is created on Swing’s event-dispatch thread. The timer starts when the panel becomes displayable and stops when it is removed. A copied Graphics2D context is disposed after each repaint.

Customize the tree

Try changing the branch-length multiplier from 0.70 to 0.65 in both recursive calls. The tree becomes more compact because each generation shrinks faster.

You can also adjust:

Setting Effect
LEVELS Tree detail. Each extra level approximately doubles the branch count.
130 Initial trunk length.
25 + 3 * wind Base branching angle and its variation, in degrees.
7.5 Time taken to reveal all levels.
width + 7f Width of the glow stroke.

Larger lengths, wider branching angles, or more levels may require changes to the scale or trunk position to keep the tree inside the canvas.

The complete source above is free to copy and run. Explore the SwingLoops repository for more Java animation examples.