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.

How do I animate a falling domino spiral in Java Swing?

A domino chain reaction can be animated by giving each tile a slightly later start time. In this SwingLoops example, 92 dominoes are placed on a spiral. Each one appears to fall toward the next, changing from blue to orange as it moves. You can create the effect using Java Swing and Java 2D without a physics engine or external libraries.

Domino Spiral

Domino Spiral

Source code

Save this example as DominoSpiral.java.

package org.kodejava.swing.animation;

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

public class DominoSpiral extends JPanel {
    private static final int WIDTH = 450;
    private static final int HEIGHT = 800;
    private static final int COUNT = 92;
    private static final double START = 1.0;
    private static final double DELAY = 0.065;
    private static final double FALL = 0.24;
    private static final double CYCLE = 10.0;
    private static final Color BACKGROUND = new Color(10, 17, 31);

    private final double[] x = new double[COUNT];
    private final double[] y = new double[COUNT];
    private final double[] direction = new double[COUNT];
    private final Timer timer = new Timer(16, _ -> repaint());
    private long startedAt;

    public DominoSpiral() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(BACKGROUND);

        // Place the tiles about 13 pixels apart along the spiral.
        double angle = 0;
        double pitch = 8.5;
        for (int i = 0; i < COUNT; i++) {
            double radius = 195 - pitch * angle;
            x[i] = WIDTH / 2.0 + radius * Math.cos(angle);
            y[i] = HEIGHT / 2.0 + radius * Math.sin(angle);
            angle += 13 / Math.hypot(radius, pitch);
        }

        for (int i = 0; i < COUNT - 1; i++) {
            direction[i] = Math.atan2(y[i + 1] - y[i], x[i + 1] - x[i]);
        }
        direction[COUNT - 1] = direction[COUNT - 2];
    }

    @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 Color tileColor(double progress) {
        return new Color(
                57 + (int) (193 * progress),
                171 - (int) (54 * progress),
                248 - (int) (179 * progress));
    }

    private static void drawTile(Graphics2D g, double progress) {
        double lean = 10 * progress;
        double height = 20 - 14 * progress;

        g.setColor(new Color(2, 6, 13, 150));
        g.fillOval(-5, -6, 19, 12);

        Path2D face = new Path2D.Double();
        face.moveTo(0, -4);
        face.lineTo(0, 4);
        face.lineTo(lean + 5, 4 - height);
        face.lineTo(lean + 5, -4 - height);
        face.closePath();

        g.setColor(tileColor(progress));
        g.fill(face);
        g.setColor(new Color(255, 255, 255, 155));
        g.draw(face);
    }

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

        double elapsed = (System.nanoTime() - startedAt) / 1e9;
        double t = elapsed % CYCLE;
        double fade = t < 9 ? 1 : 1 - clamp(t - 9);
        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);
            g.setComposite(java.awt.AlphaComposite.SrcOver.derive((float) fade));

            g.setColor(new Color(31, 49, 72));
            Path2D track = new Path2D.Double();
            track.moveTo(x[0], y[0]);
            for (int i = 1; i < COUNT; i++) {
                track.lineTo(x[i], y[i]);
            }
            g.draw(track);

            for (int i = 0; i < COUNT; i++) {
                double u = clamp((t - START - i * DELAY) / FALL);
                double progress = u * u * (3 - 2 * u);
                Graphics2D tile = (Graphics2D) g.create();
                try {
                    tile.translate(x[i], y[i]);
                    tile.rotate(direction[i]);
                    drawTile(tile, progress);
                } finally {
                    tile.dispose();
                }
            }
        } finally {
            g.dispose();
        }
    }

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

Run the example

Open a terminal in the directory containing the file. With a JDK installed and a desktop environment available, run:

javac DominoSpiral.java
java DominoSpiral

The window opens with a preferred drawing area of 450 × 800 pixels. Resize it to fit your screen; the drawing keeps its proportions. Close the window to exit.

Place the tiles along a spiral

The code starts with a radius of 195 pixels and reduces it by 8.5 pixels for each radian of angular travel. Sine and cosine convert the radius and angle to a position on the screen.

Using the same angle increment everywhere would spread out the outer tiles and crowd the inner ones. Instead, the code uses this approximation:

angle += 13 / Math.hypot(radius, pitch);

For a small angle change, the distance traveled along this spiral is approximately the angle change multiplied by sqrt(radius² + pitch²). Dividing the desired spacing of 13 pixels by that factor gives an angle step that grows as the spiral tightens. The result is approximately even spacing. After placing the tiles, Math.atan2() determines which direction each tile should face by looking at the next tile.

Turn a delay into a chain reaction

The first tile starts one second into the cycle. Each later tile waits an additional 65 milliseconds:

double u = clamp((t - START - i * DELAY) / FALL);

A value of zero means the tile is upright, and one means it has finished falling. The fall takes 240 milliseconds, so several neighboring tiles are in motion at once. Smoothstep, u * u * (3 - 2 * u), eases the movement at both ends.

To draw the fall, the program shifts the tile’s upper edge forward and reduces its visible height. Its color shifts toward orange at the same time. This is a stylized 2D animation: the timing creates the apparent chain reaction, and the program does not calculate contact between tiles.

Repeat the animation

A Swing timer requests repaints about every 16 milliseconds. The drawing uses elapsed time from System.nanoTime(), so a delayed repaint does not change when the next tile is supposed to fall. During the final second the spiral fades away. At the ten-second boundary, the upright tiles reappear.

Try raising DELAY from 0.065 to 0.075 to slow down the chain. If you increase it further, check that START + (COUNT - 1) * DELAY + FALL still fits before the fade begins at nine seconds.

The complete source code is free to copy and run. Find more examples in the SwingLoops repository.

How do I animate wave interference in Java Swing?

Drop two pebbles into water and the ripples overlap. Where two crests meet, they reinforce each other; where a crest meets an equally strong trough, they cancel. In this SwingLoops example, we use two sinusoidal waves to recreate that pattern pixel by pixel.

The result is a portrait animation with cyan crests, pink troughs, and dark bands where the combined displacement is small. The example uses Java Swing and Java 2D without external libraries.

Ripple Interference

Ripple Interference

Source code

Save the following code as RippleInterference.java:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class RippleInterference extends JPanel {
    private static final int W = 180, H = 320;
    private static final int AX = 52, BX = 128, SY = 160;
    private static final double TAU = 2 * Math.PI;
    private static final double CYCLE = 8.0;
    private static final Color BACKGROUND = new Color(6, 12, 26);

    private final BufferedImage image =
            new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
    private final int[] pixels =
            ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
    private final float[] sine = new float[W * H];
    private final float[] cosine = new float[W * H];
    private final Timer timer = new Timer(33, _ -> repaint());
    private long start;

    public RippleInterference() {
        setPreferredSize(new Dimension(450, 800));
        setBackground(BACKGROUND);
        for (int y = 0; y < H; y++) {
            for (int x = 0; x < W; x++) {
                int i = y * W + x;
                double a = Math.hypot(x - AX, y - SY);
                double b = Math.hypot(x - BX, y - SY);
                double ka = TAU * a / 21, kb = TAU * b / 21;
                double wa = 1 / (1 + a / 110);
                double wb = 1 / (1 + b / 110);
                sine[i] = (float) (wa * Math.sin(ka) + wb * Math.sin(kb));
                cosine[i] = (float) (wa * Math.cos(ka) + wb * Math.cos(kb));
            }
        }
    }

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

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

    private void render(double seconds) {
        double phase = TAU * 5 * ((seconds % CYCLE) / CYCLE);
        double c = Math.cos(phase), s = Math.sin(phase);
        for (int i = 0; i < pixels.length; i++) {
            // sin(k*d - phase), summed across both sources.
            double wave = sine[i] * c - cosine[i] * s;
            double glow = Math.min(1, Math.abs(wave) / 1.5);
            glow *= glow;
            int r = 6 + (int) (glow * (wave >= 0 ? 32 : 238));
            int g = 12 + (int) (glow * (wave >= 0 ? 222 : 98));
            int b = 26 + (int) (glow * (wave >= 0 ? 229 : 143));
            pixels[i] = (r << 16) | (g << 8) | b;
        }
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        drawFrame(graphics, getWidth(), getHeight(),
                  (System.nanoTime() - start) / 1e9);
    }

    void drawFrame(Graphics graphics, int width, int height, double seconds) {
        render(seconds);

        Graphics2D g = (Graphics2D) graphics.create();
        try {
            double scale = Math.min(width / (double) W,
                                    height / (double) H);
            g.translate((width - W * scale) / 2,
                        (height - H * scale) / 2);
            g.scale(scale, scale);
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                               RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(image, 0, 0, null);
            g.setColor(new Color(237, 249, 255));
            g.fillOval(AX - 2, SY - 2, 4, 4);
            g.fillOval(BX - 2, SY - 2, 4, 4);
        } finally {
            g.dispose();
        }
    }

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

Run the example

From the directory containing the source file, run:

javac RippleInterference.java
java RippleInterference

The default window is 450 × 800 pixels. Resize it to see the pattern scale while keeping its aspect ratio. Close the window to exit.

Calculate a ripple at each pixel

A circular wave depends on how far the pixel is from its source. The program finds that distance with Math.hypot():

double a = Math.hypot(x - AX, y - SY);
double ka = TAU * a / 21;
double wa = 1 / (1 + a / 110);

Here, TAU is one full turn in radians, or 2π. Dividing by 21 means the spatial phase advances by one turn every 21 image pixels. The factor wa makes the amplitude smaller as distance increases.

A source contributes wa × sin(ka − phase). As the shared time phase increases, points of equal phase move outward from the source. The program adds this contribution to the corresponding contribution from the second source.

The waves have the same frequency and start in phase. If the difference between the two distances is a whole wavelength, their oscillations reinforce each other. At half a wavelength, one oscillation opposes the other. Their amplitudes may differ because of the distance weights, so those opposing waves can leave a small residual instead of canceling completely.

Cache the parts that depend on position

Calculating each distance and calling sine twice for every pixel on every repaint would repeat work. The sources stay fixed, so the code uses the identity:

sin(k − p) = sin(k) cos(p) − cos(k) sin(p)

For each pixel, the constructor caches the sum of the two weighted spatial sines and the sum of the two weighted spatial cosines. During painting, it only needs the sine and cosine of the time phase:

double c = Math.cos(phase), s = Math.sin(phase);
double wave = sine[i] * c - cosine[i] * s;

The same values of c and s apply to all 57,600 pixels. With five turns of phase per eight-second interval, each oscillation takes 1.6 seconds.

Convert displacement to color

The sign selects cyan or pink. The magnitude controls how bright that color becomes:

double glow = Math.min(1, Math.abs(wave) / 1.5);
glow *= glow;

Squaring the normalized magnitude makes weaker values darker and emphasizes stronger peaks and troughs. A dark pixel shows low displacement at that instant; the dark lanes that persist as the ripples move reveal where the waves repeatedly oppose each other.

The renderer writes each color into an integer-backed BufferedImage and then scales the finished image with bilinear interpolation. Working at 180 × 320 keeps the per-frame calculations small while the window can display the image at a larger size.

Animate the result with Swing

A Swing timer requests a repaint approximately every 33 milliseconds. The animation reads time with System.nanoTime() instead of counting repaint events, so a late frame does not slow the intended wave motion. The window and timer run on Swing’s event-dispatch thread.

The renderer is also available through drawFrame(), which accepts a time in seconds. That makes it possible to render the same pattern into an image at a chosen instant without opening the Swing window.

Try changing the pattern

Move the sources closer together and compare the spacing of the dark bands. Then change the wavelength from 21 to 28 in both phase calculations. Keeping everything else fixed lets you see how the spacing changes with wavelength.

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

How do I morph text with particles in Java Swing?

You can turn text into a particle animation by drawing each word into a transparent image and treating its visible pixels as destinations. In this example, 840 glowing dots form JAVA, change into SwingLoops, and return to the original cloud. Everything is drawn with Java Swing and Java 2D.

Particle Text Morph

Particle Text Morph

Source code

Save the following code as ParticleTextMorph.java:

import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.swing.*;

public class ParticleTextMorph extends JPanel {
    private static final int WIDTH = 540, HEIGHT = 960, COUNT = 840;
    private static final double CYCLE = 12.0;

    private final Point[] cloud = new Point[COUNT];
    private final Point[] javaText = textPoints("JAVA", 132, 7);
    private final Point[] logoText = textPoints("SwingLoops", 90, 19);
    private final Color[] colors = new Color[COUNT];
    private final Timer timer = new Timer(16, _ -> repaint());
    private long start;

    public ParticleTextMorph() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(new Color(7, 10, 24));
        Random random = new Random(42);
        for (int i = 0; i < COUNT; i++) {
            cloud[i] = new Point(
                    40 + random.nextInt(WIDTH - 80),
                    190 + random.nextInt(HEIGHT - 380));
            float hue = 0.47f + 0.25f * random.nextFloat();
            colors[i] = Color.getHSBColor(hue, 0.55f, 1.0f);
        }
    }

    private static Point[] textPoints(String text, int size, long seed) {
        BufferedImage mask = new BufferedImage(
                WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = mask.createGraphics();
        try {
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            Font font = new Font(Font.SANS_SERIF, Font.BOLD, size);
            while (font.getSize() > 1
                    && g.getFontMetrics(font).stringWidth(text) > WIDTH - 80) {
                font = font.deriveFont(font.getSize2D() - 1);
            }
            g.setFont(font);
            FontMetrics metrics = g.getFontMetrics();
            int x = (WIDTH - metrics.stringWidth(text)) / 2;
            int y = (HEIGHT + metrics.getAscent() - metrics.getDescent()) / 2;
            g.setColor(Color.WHITE);
            g.drawString(text, x, y);
        } finally {
            g.dispose();
        }

        List<Point> pixels = new ArrayList<>();
        for (int y = 0; y < HEIGHT; y += 2) {
            for (int x = 0; x < WIDTH; x += 2) {
                if ((mask.getRGB(x, y) >>> 24) > 180) {
                    pixels.add(new Point(x, y));
                }
            }
        }
        if (pixels.isEmpty()) {
            throw new IllegalArgumentException("No visible pixels for: " + text);
        }
        Collections.shuffle(pixels, new Random(seed));
        Point[] points = new Point[COUNT];
        for (int i = 0; i < COUNT; i++) {
            points[i] = pixels.get(i % pixels.size());
        }
        return points;
    }

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

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

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

    @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 t = ((System.nanoTime() - start) / 1e9) % CYCLE;
            Point[] from;
            Point[] to;
            double u;

            if (t < 3) {
                from = cloud; to = javaText; u = t / 3;
            } else if (t < 5) {
                from = javaText; to = javaText; u = 0;
            } else if (t < 8) {
                from = javaText; to = logoText; u = (t - 5) / 3;
            } else if (t < 9) {
                from = logoText; to = logoText; u = 0;
            } else {
                from = logoText; to = cloud; u = (t - 9) / 3;
            }

            double blend = smooth(u);
            double arc = 46 * Math.sin(Math.PI * blend);
            Ellipse2D.Double dot = new Ellipse2D.Double();

            for (int i = 0; i < COUNT; i++) {
                double x = from[i].x + (to[i].x - from[i].x) * blend;
                double y = from[i].y + (to[i].y - from[i].y) * blend;
                x += arc * Math.cos(i * 2.39996);
                y += arc * Math.sin(i * 2.39996);

                g.setColor(colors[i]);
                g.setComposite(AlphaComposite.SrcOver.derive(0.12f));
                dot.setFrame(x - 5, y - 5, 10, 10);
                g.fill(dot);

                g.setComposite(AlphaComposite.SrcOver);
                dot.setFrame(x - 1.6, y - 1.6, 3.2, 3.2);
                g.fill(dot);
            }
        } finally {
            g.dispose();
        }
    }

    static void main() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingLoops - Particle Text Morph");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new ParticleTextMorph());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Run the example

Open a terminal in the directory containing the file and run:

javac ParticleTextMorph.java
java ParticleTextMorph

The application opens a portrait window with a preferred drawing area of 540 × 960. If it is too tall for your screen, change the preferred size to 405 × 720. The drawing scales to the window while preserving its proportions. Close the window to stop the animation.

Turning letters into particle destinations

The textPoints() method calls drawString() on a transparent BufferedImage. Swing never displays this image directly. Its purpose is to tell the program where the letters are.

The program visits every second pixel on both axes. A pixel is eligible when its alpha channel, a value from 0 (transparent) to 255 (opaque), exceeds 180:

if ((mask.getRGB(x, y) >>> 24) > 180) {
    pixels.add(new Point(x, y));
}

The unsigned shift extracts alpha from the packed ARGB value. The threshold mostly keeps the solid part of each letter and discards faint pixels along antialiased edges.

The program shuffles the eligible coordinates with a fixed seed so it can pick points across the word instead of filling it from top to bottom. If fewer coordinates are available than particles, modulo indexing reuses some coordinates. This work happens once for each word when the panel is created.

Moving a particle between two points

Each particle has three destinations: a point in the cloud, a point in JAVA, and a point in SwingLoops. All three arrays use the same particle index. During a transition, the program interpolates between the current and next destinations:

double x = from[i].x + (to[i].x - from[i].x) * blend;
double y = from[i].y + (to[i].y - from[i].y) * blend;

A blend of 0 gives the starting position. A blend of 0.5 gives the midpoint, and a blend of 1 gives the destination. Instead of using elapsed progress directly, the code passes it through a smoothstep function:

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

The curve starts and ends with a slope of zero. That gives the particles time to accelerate away from a word and slow down as they settle into the next one.

The sine term adds a temporary offset to the straight path. It is zero at both endpoints and largest halfway through. The offset direction depends on the particle index, so the dots bend in different directions without missing their destinations.

Drawing the glow and repeating the motion

Each particle is drawn twice: a wide translucent circle creates a halo and a smaller opaque circle forms the bright center. Both use the same color. The panel clears the background on every repaint, so this glow does not depend on retaining previous frames.

A Swing timer requests a repaint approximately every 16 milliseconds. The code calculates positions from elapsed time rather than counting frames. During the first three seconds the particles gather into JAVA; they hold for two seconds, morph for three, hold for one, then spend three seconds returning to the original cloud. The last destination is also the next cycle’s starting position, so no particle needs to jump when the clock wraps.

The window is created on Swing’s event-dispatch thread. The timer starts when the panel becomes displayable and stops when it is removed.

Customize the animation

Try replacing JAVA with your initials. The example reduces the font size to fit the available width, but short words generally leave more room for distinct particles. To compare straight and curved paths, set the arc multiplier from 46 to 0 and run the example again.

The full source code above is free to copy and run. Find more examples in the SwingLoops repository.

How do I create interactive fireworks using Java Swing?

You can create interactive fireworks in Java Swing by combining Graphics2D, mouse events, and a javax.swing.Timer. Rockets travel toward the position you click, then explode into colorful particles affected by gravity, damping, and fading.

The effect does not require an external graphics library, physics engine, or image assets.

In this SwingLoops example, fireworks launch into a dark night sky above a simple city skyline. Each explosion produces dozens of glowing particles with different colors and movement patterns. You can click several positions to create multiple explosions, and the program launches fireworks automatically when you leave it running.

Interactive Fireworks

Interactive Fireworks

Source code

Save the following code as InteractiveFireworks.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;

public class InteractiveFireworks extends JPanel {
    private static final int W = 540, H = 960;
    private final Random random = new Random();
    private final java.util.List<Rocket> rockets = new ArrayList<>();
    private final java.util.List<Particle> particles = new ArrayList<>();
    private final Timer timer = new Timer(16, e -> update());
    private long lastLaunch;

    public InteractiveFireworks() {
        setPreferredSize(new Dimension(W, H));
        setBackground(new Color(3, 5, 20));

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                double x = e.getX() * W / (double) getWidth();
                double y = e.getY() * H / (double) getHeight();
                launch(x, y);
            }
        });
    }

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

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

    private void launch(double tx, double ty) {
        double x = 40 + random.nextDouble() * (W - 80);
        double y = H;
        double dx = tx - x;
        double dy = ty - y;
        double distance = Math.max(1, Math.hypot(dx, dy));
        double speed = 9 + random.nextDouble() * 3;

        rockets.add(new Rocket(x, y,
                dx / distance * speed,
                dy / distance * speed,
                tx, ty, random.nextFloat()));
    }

    private void update() {
        long now = System.currentTimeMillis();

        if (now - lastLaunch >= 1700) {
            launch(80 + random.nextDouble() * (W - 160),
                    100 + random.nextDouble() * 350);
            lastLaunch = now;
        }

        for (Iterator<Rocket> it = rockets.iterator(); it.hasNext();) {
            Rocket r = it.next();
            double remaining = Point2D.distance(
                    r.x, r.y, r.tx, r.ty);

            if (remaining <= Math.hypot(r.vx, r.vy)) {
                r.x = r.tx;
                r.y = r.ty;
                explode(r);
                it.remove();
            } else {
                r.x += r.vx;
                r.y += r.vy;
            }
        }

        for (Iterator<Particle> it = particles.iterator();
             it.hasNext();) {
            Particle p = it.next();

            p.px = p.x;
            p.py = p.y;
            p.x += p.vx;
            p.y += p.vy;
            p.vx *= .988;
            p.vy = p.vy * .988 + .075;
            p.life -= .013f;

            if (p.life <= 0) it.remove();
        }

        repaint();
    }

    private void explode(Rocket r) {
        int count = 80 + random.nextInt(30);
        int pattern = random.nextInt(3);

        for (int i = 0; i < count; i++) {
            double angle = pattern == 2
                    ? random.nextDouble() * Math.PI * 2
                    : i * Math.PI * 2 / count;

            double speed = 2 + random.nextDouble() * 4;

            if (pattern == 1) {
                speed *= .5 + Math.abs(Math.sin(angle * 2));
            }

            particles.add(new Particle(r.x, r.y,
                    Math.cos(angle) * speed,
                    Math.sin(angle) * speed,
                    r.hue + random.nextFloat() * .08f));
        }
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        Graphics2D g = (Graphics2D) graphics.create();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.scale(getWidth() / (double) W,
                getHeight() / (double) H);

        g.setPaint(new GradientPaint(0, 0,
                new Color(3, 5, 20),
                0, H, new Color(20, 9, 44)));
        g.fillRect(0, 0, W, H);

        drawCity(g);

        for (Rocket r : rockets) {
            g.setColor(Color.WHITE);
            g.fill(new Ellipse2D.Double(r.x - 3, r.y - 3, 6, 6));
            g.setColor(new Color(255, 190, 100, 100));
            g.setStroke(new BasicStroke(3));
            g.draw(new Line2D.Double(
                    r.x, r.y + 18, r.x, r.y));
        }

        for (Particle p : particles) {
            Color c = Color.getHSBColor(p.hue % 1f, .8f, 1f);
            int alpha = (int) (p.life * 230);

            g.setColor(new Color(c.getRed(),
                    c.getGreen(), c.getBlue(), alpha / 4));
            g.fill(new Ellipse2D.Double(
                    p.x - 8, p.y - 8, 16, 16));

            g.setColor(new Color(c.getRed(),
                    c.getGreen(), c.getBlue(), alpha));
            g.setStroke(new BasicStroke(2,
                    BasicStroke.CAP_ROUND,
                    BasicStroke.JOIN_ROUND));
            g.draw(new Line2D.Double(p.px, p.py, p.x, p.y));
            g.fill(new Ellipse2D.Double(
                    p.x - 2, p.y - 2, 4, 4));
        }

        g.dispose();
    }

    private void drawCity(Graphics2D g) {
        for (int i = 0; i < 18; i++) {
            int x = i * 32;
            int height = 45 + (i * 37) % 110;

            g.setColor(new Color(8, 12, 28));
            g.fillRect(x, H - height, 35, height);

            g.setColor(new Color(255, 205, 90, 100));
            for (int y = H - height + 12; y < H - 8; y += 18) {
                g.fillRect(x + 8, y, 4, 6);
                g.fillRect(x + 22, y, 4, 6);
            }
        }
    }

    private static class Rocket {
        double x, y, vx, vy, tx, ty;
        float hue;

        Rocket(double x, double y, double vx, double vy,
               double tx, double ty, float hue) {
            this.x = x;
            this.y = y;
            this.vx = vx;
            this.vy = vy;
            this.tx = tx;
            this.ty = ty;
            this.hue = hue;
        }
    }

    private static class Particle {
        double x, y, px, py, vx, vy;
        float hue, life = 1f;

        Particle(double x, double y,
                 double vx, double vy, float hue) {
            this.x = this.px = x;
            this.y = this.py = y;
            this.vx = vx;
            this.vy = vy;
            this.hue = hue;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingLoops - Fireworks");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new InteractiveFireworks());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Run the example

You need Java 17 or later and a desktop environment capable of running Swing applications.

Open a terminal in the directory containing InteractiveFireworks.java, then compile and run it:

javac InteractiveFireworks.java
java InteractiveFireworks

A window with a preferred drawing area of 540 × 960 pixels opens. Fireworks launch automatically every 1.7 seconds.

Click anywhere in the window to launch a rocket toward that position. Clicking several locations creates multiple simultaneous explosions.

You can change the preferred panel size if the window is too large for your screen.

How does the animation work?

Updating the animation with a Swing Timer

The application uses a javax.swing.Timer to update the animation approximately every 16 milliseconds:

private final Timer timer = new Timer(16, e -> update());

Each update moves the rockets, updates the particles, removes expired objects, and requests a repaint.

The timer starts in addNotify() and stops in removeNotify(), preventing the animation from continuing after the panel is removed.

Because the timer executes its callback on Swing’s Event Dispatch Thread, mouse events, animation updates, and painting share the same thread.

Moving rockets toward the target

Each rocket starts near the bottom of the screen and receives a velocity pointing toward its target.

The direction is calculated from the difference between the target and starting positions:

double dx = tx - x;
double dy = ty - y;
double distance = Math.max(1, Math.hypot(dx, dy));

Math.hypot() calculates the Euclidean distance between two points.

We divide the direction components by this distance and multiply them by the desired speed:

double vx = dx / distance * speed;
double vy = dy / distance * speed;

This ensures that the rocket moves at a consistent speed regardless of its destination.

During each animation update, its position changes according to its velocity:

r.x += r.vx;
r.y += r.vy;

Once the rocket is close enough to reach its target during the next movement, the program triggers an explosion.

Creating particles with circular motion

An explosion produces between 80 and 109 particles.

For a circular burst, each particle receives a different angle:

double angle = i * Math.PI * 2 / count;

The horizontal and vertical velocity components are calculated using:

double vx = Math.cos(angle) * speed;
double vy = Math.sin(angle) * speed;

Together, these calculations distribute particles around the explosion center.

The example also introduces variations in particle speed and direction, producing different explosion shapes.

Adding gravity and damping

After an explosion, particles move independently.

Each frame applies damping and gravity:

p.vx *= .988;
p.vy = p.vy * .988 + .075;

Multiplying velocity by .988 gradually slows the particles.

The additional .075 accelerates them downward because Java2D’s Y coordinate increases toward the bottom of the screen.

The result is a curved trajectory: particles spread outward, slow down, and eventually fall.

This is a simple visual physics simulation rather than a fully realistic model, but it works well for a fireworks animation.

Creating fading particles

Each particle begins with a lifetime of 1.0:

float life = 1f;

Its lifetime decreases with every update:

p.life -= .013f;

The remaining lifetime determines the particle’s transparency:

int alpha = (int) (p.life * 230);

As life approaches zero, the particle becomes less visible.

Expired particles are removed using the iterator, which also prevents the particle collection from growing indefinitely.

Creating a glow effect

The glow is produced by drawing each particle twice.

First, a larger circle is drawn with low opacity:

g.setColor(new Color(
        c.getRed(), c.getGreen(), c.getBlue(), alpha / 4));

g.fill(new Ellipse2D.Double(
        p.x - 8, p.y - 8, 16, 16));

A small, brighter particle is then drawn on top.

The application also draws a short line between each particle’s previous and current positions, creating a glowing motion trail.

This approximates a neon effect using ordinary Java2D shapes, without shaders or blur filters.

Generating firework colors

The example uses Color.getHSBColor() to generate colors:

Color c = Color.getHSBColor(p.hue % 1f, .8f, 1f);

Each rocket receives a random hue, and its particles use nearby hue values.

This gives every explosion a recognizable color theme while still allowing subtle variation between individual particles.

Drawing the night sky

The background uses a GradientPaint that transitions from dark navy to deep purple.

A simple city skyline is drawn using rectangles, with smaller yellow rectangles representing illuminated windows.

These elements provide context for the fireworks without requiring image assets.

Customize the animation

Try changing one parameter at a time to see how it affects the result.

Parameter Effect
16 in the timer Animation update interval in milliseconds
1700 Time between automatic launches
80 + random.nextInt(30) Number of particles per explosion
9 + random.nextDouble() * 3 Rocket speed
.988 Particle damping; smaller values slow particles faster
.075 Gravity; larger values make particles fall faster
.013f Lifetime reduction; larger values make particles disappear sooner
new Color(3, 5, 20) Background color

For example, increasing the particle count to 150 makes each firework look fuller, but also increases the amount of rendering work.

Reducing gravity creates a floating, almost magical explosion, while increasing gravity makes particles fall more quickly.

Experimenting with these values is an easy way to create your own animation style.

The complete example uses only Java Swing and Java2D. No external libraries, physics engines, or image assets are required.

Happy coding!