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.

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 build an analog world clock widget in Java Swing?

You can build a desktop world clock in Java Swing by converting one Instant into several time zones and drawing each clock face with Java 2D. This example displays an analog dial, a digital time, the local date, and the UTC offset for each city. The widget can stay above other windows while you work.

Java Swing world clock widget with analog dials for Denpasar, Jakarta, Tokyo, London, and New York

Source code

Save the source as WorldClock.java. The example uses Java 17 or later and runs with the standard JDK.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.prefs.Preferences;

public final class WorldClock {
    private static final Color BACKGROUND = new Color(13, 21, 35);
    private static final Color CARD = new Color(24, 36, 54);
    private static final Color TEXT = new Color(240, 245, 250);
    private static final Color MUTED = new Color(166, 184, 205);
    private static final Color[] ACCENTS = {
            new Color(121, 224, 196), new Color(247, 190, 118),
            new Color(165, 186, 255), new Color(250, 158, 175)
    };
    private static final DateTimeFormatter DATE =
            DateTimeFormatter.ofPattern("EEE, d MMM", Locale.ENGLISH);
    private static final DateTimeFormatter[] TIME_FORMATS = {
            DateTimeFormatter.ofPattern("HH:mm", Locale.ROOT),
            DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ROOT),
            DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH),
            DateTimeFormatter.ofPattern("h:mm:ss a", Locale.ENGLISH)
    };
    private static final String[] CITY_DATA = {
            "Amsterdam|Europe/Amsterdam", "Auckland|Pacific/Auckland", "Bangkok|Asia/Bangkok",
            "Beijing|Asia/Shanghai", "Berlin|Europe/Berlin", "Denpasar|Asia/Makassar",
            "Dubai|Asia/Dubai", "Hong Kong|Asia/Hong_Kong", "Honolulu|Pacific/Honolulu",
            "Istanbul|Europe/Istanbul", "Jakarta|Asia/Jakarta", "Johannesburg|Africa/Johannesburg",
            "Kuala Lumpur|Asia/Kuala_Lumpur", "London|Europe/London",
            "Los Angeles|America/Los_Angeles", "Manila|Asia/Manila",
            "Mexico City|America/Mexico_City", "Moscow|Europe/Moscow", "New Delhi|Asia/Kolkata",
            "New York|America/New_York", "Paris|Europe/Paris", "Perth|Australia/Perth",
            "São Paulo|America/Sao_Paulo", "Seoul|Asia/Seoul", "Singapore|Asia/Singapore",
            "Sydney|Australia/Sydney", "Tokyo|Asia/Tokyo", "Toronto|America/Toronto",
            "UTC|UTC", "Vancouver|America/Vancouver"
    };
    private static final String DEFAULTS = "Denpasar|Jakarta|Tokyo|London|New York";
    private static final List<City> CATALOG = java.util.Arrays.stream(CITY_DATA)
            .map(entry -> entry.split("\\|"))
            .map(parts -> new City(parts[0], ZoneId.of(parts[1])))
            .toList();

    private record City(String name, ZoneId zone) {
        @Override
        public String toString() {
            return name;
        }
    }

    private final JFrame frame = new JFrame("World Clock");
    private final JPanel content = new JPanel(new BorderLayout(0, 10));
    private final JPanel list = new JPanel();
    private final JScrollPane scroll = new JScrollPane(list);
    private final List<City> cities = new ArrayList<>();
    private final List<CityCard> cards = new ArrayList<>();
    private final Preferences settings;
    private final Timer timer = new Timer(50, event -> refreshClocks());
    private final JLabel empty = label("Use + City to add a clock.", 13, MUTED);
    private TrayIcon trayIcon;
    private boolean seconds;
    private boolean twelveHour;
    private boolean compact;

    private WorldClock(boolean preview) {
        settings = preview ? null : Preferences.userNodeForPackage(WorldClock.class)
                .node("world-clock-swing");
        boolean pinned = settings == null || settings.getBoolean("pinned", true);
        seconds = settings == null || settings.getBoolean("seconds", true);
        twelveHour = settings != null && settings.getBoolean("twelveHour", false);
        compact = settings != null && settings.getBoolean("compact", false);
        String names = settings == null ? DEFAULTS : settings.get("cities", DEFAULTS);
        for (String name : names.split("\\|")) {
            CATALOG.stream().filter(city -> city.name().equals(name) && !cities.contains(city))
                    .findFirst().ifPresent(cities::add);
        }

        frame.setUndecorated(true);
        frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        frame.setAlwaysOnTop(pinned);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent event) {
                hideWidget();
            }
        });
        content.setBackground(BACKGROUND);
        content.setBorder(new EmptyBorder(10, 12, 12, 12));
        frame.setContentPane(content);

        JPanel header = new JPanel(new BorderLayout(8, 0));
        header.setOpaque(false);
        JLabel title = label("World Clock", 20, TEXT);
        title.setFont(title.getFont().deriveFont(Font.BOLD));
        header.add(title, BorderLayout.CENTER);
        JPanel actions = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 0));
        actions.setOpaque(false);
        JButton add = button("+ City");
        JButton options = button("Options");
        JButton hide = button("−");
        hide.setToolTipText("Hide widget");
        hide.getAccessibleContext().setAccessibleName("Hide widget");
        add.addActionListener(event -> addCity());
        options.addActionListener(event -> showOptions(options));
        hide.addActionListener(event -> hideWidget());
        actions.add(add);
        actions.add(options);
        actions.add(hide);
        header.add(actions, BorderLayout.EAST);
        enableDrag(title);
        enableDrag(header);
        content.add(header, BorderLayout.NORTH);

        list.setLayout(new BoxLayout(list, BoxLayout.Y_AXIS));
        list.setBackground(BACKGROUND);
        scroll.setBorder(null);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroll.getVerticalScrollBar().setUnitIncrement(24);
        content.add(scroll, BorderLayout.CENTER);
        frame.getRootPane().registerKeyboardAction(event -> hideWidget(),
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);

        Rectangle area = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
        frame.setBounds(area.x + area.width - 384, area.y + 24, 360, 200);
        if (settings != null) {
            frame.setLocation(settings.getInt("x", frame.getX()), settings.getInt("y", frame.getY()));
        }
        rebuildCards();
        if (!preview) installTray();
    }

    private static JLabel label(String text, int size, Color color) {
        JLabel label = new JLabel(text);
        label.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, size));
        label.setForeground(color);
        return label;
    }

    private static JButton button(String text) {
        JButton button = new JButton(text);
        button.setBackground(CARD);
        button.setForeground(TEXT);
        button.setMargin(new Insets(4, 8, 4, 8));
        return button;
    }

    private void enableDrag(Component target) {
        MouseAdapter drag = new MouseAdapter() {
            private Point offset;

            @Override
            public void mousePressed(MouseEvent event) {
                if (!SwingUtilities.isLeftMouseButton(event)) return;
                Point pointer = event.getLocationOnScreen();
                offset = new Point(pointer.x - frame.getX(), pointer.y - frame.getY());
            }

            @Override
            public void mouseDragged(MouseEvent event) {
                if (offset == null) return;
                Point pointer = event.getLocationOnScreen();
                frame.setLocation(pointer.x - offset.x, pointer.y - offset.y);
            }

            @Override
            public void mouseReleased(MouseEvent event) {
                if (offset == null) return;
                offset = null;
                fitToScreen();
                save();
            }
        };
        target.addMouseListener(drag);
        target.addMouseMotionListener(drag);
    }

    private void fitToScreen() {
        GraphicsConfiguration screen = frame.getGraphicsConfiguration();
        Rectangle area = new Rectangle(screen.getBounds());
        Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(screen);
        area.x += insets.left;
        area.y += insets.top;
        area.width -= insets.left + insets.right;
        area.height -= insets.top + insets.bottom;
        Dimension preferred = content.getPreferredSize();
        int width = Math.min(area.width, 360);
        int height = Math.min(area.height, preferred.height);
        int x = Math.max(area.x, Math.min(frame.getX(), area.x + area.width - width));
        int y = Math.max(area.y, Math.min(frame.getY(), area.y + area.height - height));
        frame.setBounds(x, y, width, height);
    }

    private void addCity() {
        City[] available = CATALOG.stream().filter(city -> !cities.contains(city)).toArray(City[]::new);
        if (available.length == 0) {
            JOptionPane.showMessageDialog(frame, "All cities are already displayed.");
            return;
        }
        City choice = (City) JOptionPane.showInputDialog(frame, "Choose a city or time zone",
                "Add City", JOptionPane.PLAIN_MESSAGE, null, available, available[0]);
        if (choice == null) return;
        cities.add(choice);
        rebuildCards();
        save();
        CityCard added = cards.get(cards.size() - 1);
        SwingUtilities.invokeLater(() -> list.scrollRectToVisible(added.getBounds()));
    }

    private void showOptions(JButton anchor) {
        JPopupMenu menu = new JPopupMenu();
        toggle(menu, "Always on top", frame.isAlwaysOnTop(), frame::setAlwaysOnTop);
        toggle(menu, "Show seconds", seconds, value -> seconds = value);
        toggle(menu, "12-hour format", twelveHour, value -> twelveHour = value);
        toggle(menu, "Compact layout", compact, value -> {
            compact = value;
            rebuildCards();
        });
        menu.addSeparator();
        item(menu, "Exit", true, this::exit);
        menu.show(anchor, 0, anchor.getHeight());
    }

    private void toggle(JPopupMenu menu, String title, boolean checked,
                        java.util.function.Consumer<Boolean> change) {
        JCheckBoxMenuItem item = new JCheckBoxMenuItem(title, checked);
        item.addActionListener(event -> {
            change.accept(item.isSelected());
            refreshClocks();
            save();
        });
        menu.add(item);
    }

    private static void item(JPopupMenu menu, String title, boolean enabled, Runnable action) {
        JMenuItem item = new JMenuItem(title);
        item.setEnabled(enabled);
        item.addActionListener(event -> action.run());
        menu.add(item);
    }

    private void showCityMenu(JButton anchor, City city) {
        int index = cities.indexOf(city);
        JPopupMenu menu = new JPopupMenu();
        item(menu, "Move up", index > 0, () -> moveCity(index, index - 1));
        item(menu, "Move down", index < cities.size() - 1, () -> moveCity(index, index + 1));
        item(menu, "Remove", true, () -> {
            cities.remove(city);
            rebuildCards();
            save();
        });
        menu.show(anchor, 0, anchor.getHeight());
    }

    private void moveCity(int index, int destination) {
        City city = cities.remove(index);
        cities.add(destination, city);
        rebuildCards();
        save();
        CityCard moved = cards.get(destination);
        SwingUtilities.invokeLater(() -> list.scrollRectToVisible(moved.getBounds()));
    }

    private void rebuildCards() {
        list.removeAll();
        cards.clear();
        if (cities.isEmpty()) {
            empty.setBorder(new EmptyBorder(12, 8, 12, 8));
            list.add(empty);
        }
        for (int index = 0; index < cities.size(); index++) {
            if (index > 0) list.add(Box.createVerticalStrut(6));
            City city = cities.get(index);
            Color accent = ACCENTS[CATALOG.indexOf(city) % ACCENTS.length];
            CityCard card = new CityCard(city, accent);
            cards.add(card);
            list.add(card);
        }
        list.revalidate();
        fitToScreen();
        list.repaint();
        refreshClocks();
    }

    private void refreshClocks() {
        Instant now = Instant.now();
        LocalDate localDate = now.atZone(ZoneId.systemDefault()).toLocalDate();
        int formatIndex = (twelveHour ? 2 : 0) + (seconds ? 1 : 0);
        for (CityCard card : cards) {
            ZonedDateTime cityTime = now.atZone(card.city.zone());
            card.refresh(cityTime, localDate, TIME_FORMATS[formatIndex]);
        }
    }

    private void save() {
        if (settings == null) return;
        settings.put("cities", String.join("|", cities.stream().map(City::name).toList()));
        settings.putInt("x", frame.getX());
        settings.putInt("y", frame.getY());
        settings.putBoolean("pinned", frame.isAlwaysOnTop());
        settings.putBoolean("seconds", seconds);
        settings.putBoolean("twelveHour", twelveHour);
        settings.putBoolean("compact", compact);
    }

    private void installTray() {
        if (!SystemTray.isSupported()) return;
        BufferedImage icon = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = icon.createGraphics();
        try {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setColor(CARD);
            g.fillOval(0, 0, 32, 32);
            g.setColor(ACCENTS[0]);
            g.setStroke(new BasicStroke(2.4f));
            g.drawOval(3, 3, 26, 26);
            g.drawLine(16, 16, 16, 7);
            g.drawLine(16, 16, 23, 20);
        } finally {
            g.dispose();
        }
        PopupMenu menu = new PopupMenu();
        MenuItem show = new MenuItem("Show World Clock");
        show.addActionListener(event -> SwingUtilities.invokeLater(this::showWidget));
        menu.add(show);
        MenuItem close = new MenuItem("Exit");
        close.addActionListener(event -> SwingUtilities.invokeLater(this::exit));
        menu.add(close);
        TrayIcon iconCandidate = new TrayIcon(icon, "World Clock", menu);
        iconCandidate.setImageAutoSize(true);
        iconCandidate.addActionListener(event -> SwingUtilities.invokeLater(this::showWidget));
        try {
            SystemTray.getSystemTray().add(iconCandidate);
            trayIcon = iconCandidate;
        } catch (AWTException error) {
            // The taskbar remains available if a tray icon cannot be registered.
        }
    }

    private void showWidget() {
        fitToScreen();
        frame.setExtendedState(JFrame.NORMAL);
        frame.setVisible(true);
        frame.toFront();
        refreshClocks();
        timer.start();
    }

    private void hideWidget() {
        if (trayIcon != null) {
            timer.stop();
            frame.setVisible(false);
        } else {
            frame.setExtendedState(JFrame.ICONIFIED);
        }
    }

    private void exit() {
        timer.stop();
        save();
        if (trayIcon != null) SystemTray.getSystemTray().remove(trayIcon);
        frame.dispose();
    }

    private final class CityCard extends JPanel {
        private final City city;
        private final Dial dial;
        private final JLabel digital = label("", compact ? 17 : 21, TEXT);
        private final JLabel date = label("", 12, MUTED);

        CityCard(City city, Color accent) {
            super(new BorderLayout(10, 0));
            this.city = city;
            setOpaque(false);
            setBorder(new EmptyBorder(6, 9, 6, 8));
            int height = compact ? 70 : 104;
            setPreferredSize(new Dimension(320, height));
            setMaximumSize(new Dimension(Integer.MAX_VALUE, height));
            setAlignmentX(Component.LEFT_ALIGNMENT);
            dial = new Dial(accent, height - 12);
            add(dial, BorderLayout.WEST);

            JPanel info = new JPanel(new GridBagLayout());
            info.setOpaque(false);
            JPanel text = new JPanel();
            text.setOpaque(false);
            text.setLayout(new BoxLayout(text, BoxLayout.Y_AXIS));
            JLabel name = label(city.name(), 13, accent);
            name.setFont(name.getFont().deriveFont(Font.BOLD));
            digital.setFont(new Font(Font.MONOSPACED, Font.BOLD, compact ? 17 : 21));
            text.add(name);
            text.add(digital);
            text.add(date);
            GridBagConstraints layout = new GridBagConstraints();
            layout.weightx = 1;
            layout.fill = GridBagConstraints.HORIZONTAL;
            info.add(text, layout);
            add(info, BorderLayout.CENTER);
            JButton actions = button("⋯");
            actions.setMargin(new Insets(2, 5, 2, 5));
            actions.getAccessibleContext().setAccessibleName("Options for " + city.name());
            actions.addActionListener(event -> showCityMenu(actions, city));
            JPanel actionPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 2));
            actionPanel.setOpaque(false);
            actionPanel.add(actions);
            add(actionPanel, BorderLayout.EAST);
        }

        void refresh(ZonedDateTime time, LocalDate localDate, DateTimeFormatter format) {
            long difference = ChronoUnit.DAYS.between(localDate, time.toLocalDate());
            String day = difference == 0 ? "" : String.format(Locale.ROOT, "  ·  %+dd", difference);
            String offset = time.getOffset().equals(ZoneOffset.UTC) ? "+00:00" : time.getOffset().getId();
            digital.setText(time.format(format));
            date.setText(time.format(DATE) + "  ·  UTC" + offset + day);
            dial.update(time, seconds);
        }

        @Override
        protected void paintComponent(Graphics graphics) {
            super.paintComponent(graphics);
            Graphics2D g = (Graphics2D) graphics.create();
            try {
                g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g.setColor(CARD);
                g.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);
            } finally {
                g.dispose();
            }
        }
    }

    private static final class Dial extends JComponent {
        private final Color accent;
        private ZonedDateTime time;
        private boolean showSeconds;

        Dial(Color accent, int size) {
            this.accent = accent;
            setPreferredSize(new Dimension(size, size));
        }

        void update(ZonedDateTime nextTime, boolean seconds) {
            boolean minuteChanged = time == null ||
                                    !time.truncatedTo(ChronoUnit.MINUTES).equals(nextTime.truncatedTo(ChronoUnit.MINUTES));
            boolean repaintNeeded = seconds || minuteChanged || showSeconds != seconds;
            time = nextTime;
            showSeconds = seconds;
            if (repaintNeeded) repaint();
        }

        @Override
        protected void paintComponent(Graphics graphics) {
            super.paintComponent(graphics);
            if (time == null) return;
            Graphics2D g = (Graphics2D) graphics.create();
            try {
                g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                double size = Math.min(getWidth(), getHeight());
                g.translate(getWidth() / 2.0, getHeight() / 2.0);
                g.scale(size / 100.0, size / 100.0);

                g.setPaint(new GradientPaint(-35, -48, new Color(49, 70, 93),
                        30, 49, new Color(11, 19, 33)));
                g.fill(new Ellipse2D.Double(-48, -48, 96, 96));
                g.setColor(accent);
                g.setStroke(new BasicStroke(1.6f));
                g.draw(new Ellipse2D.Double(-46, -46, 92, 92));
                g.setPaint(new RadialGradientPaint(new Point2D.Double(-13, -17), 65,
                        new float[]{0, 1}, new Color[]{new Color(42, 59, 79), new Color(9, 16, 29)}));
                g.fill(new Ellipse2D.Double(-43, -43, 86, 86));

                for (int tick = 0; tick < 60; tick++) {
                    boolean hour = tick % 5 == 0;
                    double angle = tick * Math.PI / 30;
                    g.setColor(hour ? accent : new Color(102, 124, 149));
                    g.setStroke(new BasicStroke(hour ? 1.7f : 0.7f, BasicStroke.CAP_ROUND,
                            BasicStroke.JOIN_ROUND));
                    g.draw(radialLine(angle, hour ? 35 : 38, 40));
                }

                g.setColor(TEXT);
                g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 9));
                numeral(g, "12", 0, -27);
                numeral(g, "3", 27, 0);
                numeral(g, "6", 0, 27);
                numeral(g, "9", -27, 0);

                double second = showSeconds ? time.getSecond() + time.getNano() / 1_000_000_000.0 : 0;
                double minute = time.getMinute() + second / 60;
                double hour = time.getHour() % 12 + minute / 60;
                hand(g, hour / 12, 23, 4.3f, TEXT);
                hand(g, minute / 60, 33, 2.9f, TEXT);
                if (showSeconds) hand(g, second / 60, 36, 1.4f, accent);
                g.setColor(accent);
                g.fill(new Ellipse2D.Double(-3.5, -3.5, 7, 7));
                g.setColor(BACKGROUND);
                g.fill(new Ellipse2D.Double(-1.3, -1.3, 2.6, 2.6));
            } finally {
                g.dispose();
            }
        }

        private static void numeral(Graphics2D g, String text, int x, int y) {
            FontMetrics metrics = g.getFontMetrics();
            g.drawString(text, x - metrics.stringWidth(text) / 2.0f,
                    y + (metrics.getAscent() - metrics.getDescent()) / 2.0f);
        }

        private static void hand(Graphics2D g, double turn, double length, float width, Color color) {
            g.setColor(color);
            g.setStroke(new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
            g.draw(radialLine(turn * 2 * Math.PI, -5, length));
        }

        private static Line2D radialLine(double angle, double start, double end) {
            double x = Math.sin(angle);
            double y = -Math.cos(angle);
            return new Line2D.Double(x * start, y * start, x * end, y * end);
        }
    }

    private static void verifyAndRender(Path output) throws IOException {
        Instant winter = Instant.parse("2026-01-15T19:30:00Z");
        Instant summer = Instant.parse("2026-07-15T19:30:00Z");
        if (CATALOG.size() != 30 ||
            winter.atZone(ZoneId.of("Asia/Makassar")).getDayOfMonth() != 16 ||
            !winter.atZone(ZoneId.of("America/New_York")).getOffset().equals(ZoneOffset.ofHours(-5)) ||
            !summer.atZone(ZoneId.of("America/New_York")).getOffset().equals(ZoneOffset.ofHours(-4)) ||
            !summer.atZone(ZoneId.of("Europe/London")).getOffset().equals(ZoneOffset.ofHours(1))) {
            throw new IllegalStateException("Time zone check failed");
        }
        WorldClock widget = new WorldClock(true);
        try {
            widget.frame.validate();
            widget.frame.addNotify();
            widget.frame.validate();
            if (widget.cards.size() != 5 || !widget.frame.isAlwaysOnTop() ||
                widget.cards.get(0).dial.getWidth() <= 0) {
                throw new IllegalStateException("Initial widget layout check failed");
            }

            widget.moveCity(0, 1);
            if (!widget.cards.get(1).city.name().equals("Denpasar")) {
                throw new IllegalStateException("Reorder check failed");
            }
            widget.moveCity(1, 0);
            widget.frame.validate();
            for (CityCard card : widget.cards) {
                card.refresh(winter.atZone(card.city.zone()), LocalDate.of(2026, 1, 16), TIME_FORMATS[1]);
            }
            if (!widget.cards.get(0).digital.getText().equals("03:30:00") ||
                !widget.cards.get(3).date.getText().endsWith("-1d")) {
                throw new IllegalStateException("Displayed time or date check failed");
            }
            widget.frame.validate();
            if (widget.cards.get(0).digital.getWidth() <= 0 || widget.cards.get(0).date.getWidth() <= 0) {
                throw new IllegalStateException("Clock label layout check failed");
            }
            BufferedImage image = new BufferedImage(widget.content.getWidth(), widget.content.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            try {
                widget.content.printAll(g);
            } finally {
                g.dispose();
            }
            javax.imageio.ImageIO.write(image, "png", output.toFile());
            widget.compact = true;
            widget.rebuildCards();
            widget.cities.clear();
            widget.rebuildCards();
            if (!widget.cards.isEmpty() || widget.list.getComponentCount() != 1) {
                throw new IllegalStateException("Empty state check failed");
            }
        } finally {
            widget.exit();
        }
    }

    public static void main(String[] args) throws Exception {
        if (args.length == 2 && args[0].equals("--verify")) {
            SwingUtilities.invokeAndWait(() -> {
                try {
                    verifyAndRender(Path.of(args[1]));
                } catch (IOException error) {
                    throw new java.io.UncheckedIOException(error);
                }
            });
            return;
        }
        SwingUtilities.invokeLater(() -> new WorldClock(false).showWidget());
    }
}

Use one instant for every city

A world clock displays the same moment in different places. The refresh method takes one snapshot of the system clock. Each card then converts that snapshot into a ZonedDateTime using its city’s IANA time-zone ID.

Instant now = Instant.now();
ZonedDateTime denpasar = now.atZone(ZoneId.of("Asia/Makassar"));
ZonedDateTime newYork = now.atZone(ZoneId.of("America/New_York"));

Using a region-based ZoneId lets Java apply the correct offset for that instant. New York, for example, can show either UTC−05:00 or UTC−04:00 depending on the date. The offset in each card comes from ZonedDateTime.getOffset().

To show whether a city is on a different calendar day, compare its LocalDate with the date in ZoneId.systemDefault(). A card shows -1d when its date is one day behind the computer’s local date.

Draw the clock face with Java 2D

The Dial component overrides paintComponent(). It moves the graphics origin to the center of the component and scales a 100-by-100 drawing area to fit. The same drawing code therefore works for both the regular and compact layouts.

The dial uses a gradient bezel, a shaded face, and sixty tick marks. Every fifth tick is longer and uses the city’s accent color. For each tick or hand, the following helper projects two points onto the same radial line.

private static Line2D radialLine(double angle, double start, double end) {
    double x = Math.sin(angle);
    double y = -Math.cos(angle);
    return new Line2D.Double(x * start, y * start, x * end, y * end);
}

At zero radians, sin(0) is zero and -cos(0) is negative, so the line points toward twelve o’clock. A quarter turn points right toward three o’clock. A negative starting radius extends the hand a little behind the center.

When seconds are enabled, the fractional part of the second comes from getNano(). The minute hand uses the fraction of the current minute, and the hour hand uses the fraction of the current hour.

double second = showSeconds ? time.getSecond() + time.getNano() / 1_000_000_000.0 : 0;
double minute = time.getMinute() + second / 60;
double hour = time.getHour() % 12 + minute / 60;

hand(g, hour / 12, 23, 4.3f, TEXT);
hand(g, minute / 60, 33, 2.9f, TEXT);
if (showSeconds) hand(g, second / 60, 36, 1.4f, accent);

The example uses a Swing Timer with a 50 ms interval to repaint the moving second hand. Each tick reads the current time. If the event dispatch thread is briefly busy, the next refresh uses the current instant and the clock catches up automatically.

Keep the widget visible

The widget uses an undecorated JFrame and calls setAlwaysOnTop(true) by default. A mouse listener on the title lets you drag the window. The Options menu lets you switch off always-on-top, hide seconds, choose a 12-hour format, or switch to a compact layout.

+ City opens the city picker. Each card’s menu can move the city up or down or remove it. Java’s Preferences API stores the city order, window position, and display settings. When the system tray is available, the hide button moves the widget there. Otherwise, the widget minimizes to the taskbar.

Run the example

To compile and run from source, use a JDK.

javac --release 17 -encoding UTF-8 WorldClock.java
java WorldClock

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!