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





