Use SwingUtilities.invokeLater() to create and show a Swing window on the event dispatch thread (EDT). Swing uses this thread to process events such as mouse clicks and to update the interface.
This example opens a window and prints whether the code that creates it is running on the EDT.
Source code
Save the following code as SwingEdtExample.java:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class SwingEdtExample {
void main() {
IO.println("main() on the EDT: "
+ SwingUtilities.isEventDispatchThread());
SwingUtilities.invokeLater(this::showWindow);
}
private void showWindow() {
IO.println("showWindow() on the EDT: "
+ SwingUtilities.isEventDispatchThread());
JFrame frame = new JFrame("Hello, Swing!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel("Welcome to Swing", SwingConstants.CENTER));
frame.setSize(400, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
What the window looks like
The window looks like the one in the previous example. The console messages show which thread runs each method.
Explanation
When you launch the program, main() runs outside the EDT. It schedules the showWindow() method with this line:
SwingUtilities.invokeLater(this::showWindow);
The method reference this::showWindow supplies the task. invokeLater() puts that task on Swing’s event queue and returns without waiting. The EDT runs the task when it reaches the front of the queue.
The showWindow() method creates the frame and label, adds the label to the frame, and makes the window visible. All of those steps run on the EDT. Calling showWindow() directly from main() would run those steps on the main thread instead.
SwingUtilities.isEventDispatchThread() checks the thread that is running the current code. It returns false in main() and true in showWindow().
Run the example
javac SwingEdtExample.java
java SwingEdtExample
The console prints:
main() on the EDT: false
showWindow() on the EDT: true
Keep work on the EDT short. A slow operation, such as downloading a file, can keep Swing from responding to clicks or repainting the window. Run slow work in the background and send interface updates back to the EDT.
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
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.
You can simulate flying through stars by assigning each star a depth and projecting its position onto a two-dimensional panel. As the depth decreases, the star moves farther from the center of the screen and appears larger.
Starfield Warp
This SwingLoops example draws 420 stars with short light trails. It uses Java Swing and Java 2D without a 3D engine, external libraries, or image assets.
Source code
Save the following code as StarfieldWarp.java:
import java.awt.*;
import java.awt.geom.*;
import java.util.Random;
import javax.swing.*;
public class StarfieldWarp extends JPanel {
private static final int WIDTH = 450;
private static final int HEIGHT = 800;
private static final int COUNT = 420;
private static final double CYCLE = 12.0;
private static final double FOCAL = 260.0;
private final double[] x = new double[COUNT];
private final double[] y = new double[COUNT];
private final double[] offset = new double[COUNT];
private final Timer timer = new Timer(16, _ -> repaint());
private long startedAt;
public StarfieldWarp() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(new Color(5, 9, 20));
Random random = new Random(42);
for (int i = 0; i < COUNT; i++) {
double angle = random.nextDouble() * 2 * Math.PI;
double radius = 0.12 + 1.8 * Math.sqrt(random.nextDouble());
x[i] = radius * Math.cos(angle);
y[i] = radius * Math.sin(angle);
offset[i] = random.nextDouble();
}
}
@Override
public void addNotify() {
super.addNotify();
startedAt = System.nanoTime();
timer.start();
}
@Override
public void removeNotify() {
timer.stop();
super.removeNotify();
}
@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() / 2.0, getHeight() / 2.0);
g.scale(scale, scale);
g.clipRect(-WIDTH / 2, -HEIGHT / 2, WIDTH, HEIGHT);
double seconds = (System.nanoTime() - startedAt) / 1e9;
double phase = (seconds % CYCLE) / CYCLE;
for (int i = 0; i < COUNT; i++) {
double progress = (phase + offset[i]) % 1.0;
double z = 4.0 - 3.8 * progress;
double screenX = FOCAL * x[i] / z;
double screenY = FOCAL * y[i] / z;
double previousZ = Math.min(4.0, z + 0.045);
double tailX = FOCAL * x[i] / previousZ;
double tailY = FOCAL * y[i] / previousZ;
// Hide each star as it enters or leaves its depth cycle.
double fadeIn = Math.min(1, progress / 0.08);
double fadeOut = Math.min(1, (1 - progress) / 0.06);
float alpha = (float) (fadeIn * fadeOut);
float width = (float) (0.6 + 1.8 * progress);
g.setColor(new Color(110, 192, 255));
g.setComposite(
AlphaComposite.SrcOver.derive(alpha * 0.13f));
g.setStroke(new BasicStroke(width + 4f,
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
g.draw(new Line2D.Double(
tailX, tailY, screenX, screenY));
g.setColor(new Color(225, 244, 255));
g.setComposite(AlphaComposite.SrcOver.derive(alpha));
g.setStroke(new BasicStroke(width,
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
g.draw(new Line2D.Double(
tailX, tailY, screenX, screenY));
}
} finally {
g.dispose();
}
}
static void main() {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("SwingLoops - Starfield Warp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new StarfieldWarp());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Run the example
You need a Java Development Kit and a desktop environment that supports Swing windows.
Open a terminal in the directory containing the file and run:
javac StarfieldWarp.java
java StarfieldWarp
The preferred drawing area is 450 × 800 pixels. Resize the window to fit your display; the drawing preserves its proportions. Close the window to exit.
Give each star a position and a depth
Each star receives fixed horizontal and vertical coordinates, plus a random offset within the animation cycle. The random offsets spread the stars across different depths instead of making them approach together.
A star starts at depth 4.0 and approaches depth 0.2 before returning to the far end. The depth stays positive, avoiding division by zero.
The fixed random seed produces the same star arrangement on each run. The animation repeats every 12 seconds because every star completes one depth cycle in that interval.
The FOCAL constant converts the star coordinates into logical screen pixels. Dividing by depth creates perspective.
For example, a star with x = 1 is drawn at horizontal coordinate 65 when z = 4, but at coordinate 260 when z = 1. Its horizontal position in space has not changed; its projected position moves outward because it is closer.
This is the same basic relationship that makes nearby objects appear larger than distant ones.
Draw a trail behind each star
The trail begins at a slightly greater depth:
double previousZ = Math.min(4.0, z + 0.045);
Projecting that deeper point places the trail’s tail closer to the screen center. A line from the tail to the current position suggests forward motion.
Despite its name, previousZ is not a stored previous-frame position. It is a fixed depth offset, so the trail does not depend on the repaint rate. Perspective naturally makes the trail longer as the star approaches.
The code draws each line twice: a wide translucent stroke creates a soft halo, and a narrow bright stroke forms the center.
Hide the depth reset
Modulo arithmetic returns a star to the far end when its progress reaches one. Without a fade, that reset could produce a visible jump.
The first 8% of each star’s journey fades in, and the final 6% fades out. At the wrap point, the star is invisible. Many stars also leave the panel’s visible bounds before reaching their nearest depth.
This makes the repeating depth cycle less noticeable while keeping the simulation deterministic.
Animate with Swing
A Swing timer requests repaints approximately every 16 milliseconds. The program calculates motion from elapsed time measured with System.nanoTime(), rather than moving stars a fixed amount per frame.
A delayed repaint therefore skips ahead to the correct position instead of slowing down the animation.
The interface 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
Setting
Effect
COUNT
Number of stars.
CYCLE
Duration of each depth journey; smaller values increase speed.
FOCAL
Projection scale; larger values move stars farther from the center.
0.045 in the tail calculation
Trail length in depth units.
Stroke colors
Star and halo colors.
0.08 and 0.06
Fade-in and fade-out portions of each journey.
For a first experiment, reduce CYCLE from 12 to 8 seconds. Then increase the tail depth offset to 0.08 to create longer streaks.
The complete source code above is free to copy and run. Explore the SwingLoops repository for more Java animation examples.
You can create a moiré pattern by drawing two sets of parallel lines on top of one another and rotating one set slightly. Their spacing produces broad bands that appear to move as the angle changes.
Rotating Moire
This SwingLoops example uses Java Swing and Java 2D to animate the effect. It requires no external libraries or image assets.
Source code
Save the following code as RotatingMoire.java:
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class RotatingMoire extends JPanel {
private static final int WIDTH = 450;
private static final int HEIGHT = 800;
private static final int EXTENT = 700;
private static final int SPACING = 11;
private static final double CYCLE = 12.0;
private final Timer timer = new Timer(16, _ -> repaint());
private long startedAt;
private int mode = 3;
public RotatingMoire() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(new Color(9, 16, 29));
for (int i = 1; i <= 3; i++) {
final int selected = i;
String action = "mode" + i;
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke((char) ('0' + i)), action);
getActionMap().put(action, new AbstractAction() {
@Override
public void actionPerformed(
java.awt.event.ActionEvent event) {
mode = selected;
repaint();
}
});
}
}
@Override
public void addNotify() {
super.addNotify();
startedAt = System.nanoTime();
timer.start();
}
@Override
public void removeNotify() {
timer.stop();
super.removeNotify();
}
private static void layer(Graphics2D parent,
double angle, Color color) {
Graphics2D g = (Graphics2D) parent.create();
try {
g.rotate(angle);
g.setColor(color);
g.setStroke(new BasicStroke(3.5f));
for (int x = -EXTENT; x <= EXTENT; x += SPACING) {
g.draw(new Line2D.Double(
x, -EXTENT, x, EXTENT));
}
} finally {
g.dispose();
}
}
@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() / 2.0, getHeight() / 2.0);
g.scale(scale, scale);
g.clipRect(-WIDTH / 2, -HEIGHT / 2, WIDTH, HEIGHT);
double seconds = (System.nanoTime() - startedAt) / 1e9;
double phase = 2 * Math.PI * (seconds % CYCLE) / CYCLE;
double movingAngle = Math.toRadians(
10 + 7 * Math.sin(phase));
layer(g, 0, new Color(62, 202, 226, 180));
if (mode >= 2) {
layer(g, mode == 2 ? Math.toRadians(10) : movingAngle,
new Color(244, 166, 123, 180));
}
} finally {
g.dispose();
}
}
static void main() {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("SwingLoops - Rotating Moire");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new RotatingMoire());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Run the example
With a JDK 25 installed, open a terminal in the directory containing the source file:
javac RotatingMoire.java
java RotatingMoire
A desktop environment is required to display the Swing window. Close the window to stop the application.
Use these keys while the window is active:
Key
View
1
Show only the fixed cyan lines.
2
Add a stationary second layer at 10 degrees.
3
Animate the second layer.
Draw the two layers
The layer() method draws equally spaced vertical lines. Each line has the same width and extends beyond the visible canvas.
Before drawing the second layer, the code rotates its copied graphics context:
g.rotate(angle);
Java 2D transforms all subsequent line coordinates. The method disposes the copied context afterward, so its rotation does not affect the other layer.
The broad bands are not separate shapes. They emerge where the two repeating line patterns overlap.
Why do broad bands appear?
When two line grids have similar orientations, their relative alignment changes slowly across the image. Some regions contain closely aligned lines; elsewhere, the lines separate and cross. This creates a larger repeating pattern over the fine line structure.
For two ideal grids with the same spacing s and an angle difference θ, the moiré spacing is approximately:
D = s / (2 × sin(θ / 2))
Angles in this formula are in radians. As the angle difference becomes smaller, the broad bands become farther apart.
For example, with a line spacing of 11 pixels and an angle difference of 10 degrees, the idealized band spacing is about 63 pixels. Stroke width, transparency, and the screen’s sampling affect the final appearance.
This example deliberately constructs the effect from two layers. It is different from unwanted aliasing caused solely by insufficient display resolution, although resizing can introduce additional sampling effects.
Sine varies from −1 to 1, so the angle varies smoothly between 3 and 17 degrees. Keeping it away from zero avoids the extremely wide band spacing near perfect alignment.
The time phase completes one turn every 12 seconds:
At the cycle boundary, the angle returns to its starting value with matching motion, allowing the animation to repeat smoothly.
Paint safely with Swing
A Swing timer requests repaints approximately every 16 milliseconds. Actual repaint frequency depends on the event queue and system performance.
The angle uses elapsed time rather than a frame counter, so delayed frames do not change the intended cycle duration. The interface, timer callbacks, and painting run on Swing’s event-dispatch thread.
The drawing is centered, scaled uniformly, and clipped to a logical 450 × 800 canvas. This preserves its proportions when the window is resized.
Customize the effect
Try changing one setting at a time:
Setting
Effect
SPACING
Distance between lines; changes the scale of the moiré pattern.
3.5f stroke width
Changes how much each layer covers the background.
10 in the angle calculation
Average angle between layers.
7 in the angle calculation
Amount of angular variation.
CYCLE
Duration of one back-and-forth rotation.
Layer colors and alpha values
Change the contrast and overlap colors.
Start by increasing SPACING from 11 to 15. The fine lines and the broad pattern will both become more widely spaced.
The complete source code above is free to copy and run. Explore the SwingLoops repository for more Java animation examples.
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.
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:
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.