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.

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.
The star’s depth decreases over time:
double progress = (phase + offset[i]) % 1.0;
double z = 4.0 - 3.8 * progress;
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.
Project the stars onto the screen
The key equations are:
double screenX = FOCAL * x[i] / z;
double screenY = FOCAL * y[i] / z;
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.