Swing Timers and Animation - potatoscript/JavaSwing GitHub Wiki

πŸ•°οΈ Swing Timers and Animation in Java 🎨


πŸ“ What is a Timer in Java Swing?

In Java Swing, Timer is used to schedule and execute a task repeatedly after a fixed delay or at regular intervals. It is often used for creating animations, periodic updates, or time-based events in a Swing application.

The Timer class in the javax.swing package can be used to create animations, handle timeouts, and schedule repetitive tasks without blocking the main user interface thread.


πŸ“š Swing Timer Basics

The Timer is initialized with two parameters:

  1. Delay: The interval (in milliseconds) between each timer event.
  2. ActionListener: The listener that defines the action to be executed at each timer tick.

When the timer is started, it triggers the actionPerformed method of the ActionListener at regular intervals.


βœ… How Swing Timer Works?

  • Interval: The delay between each event (e.g., every 50 milliseconds).
  • ActionPerformed: The method that gets called on each timer tick.
  • Start and Stop: You can start and stop the timer whenever needed.

πŸ“š Step 1: Basic Timer Example

Let’s start by creating a simple timer that increments a counter every 1 second (1000 milliseconds).


πŸ“ Example: Basic Timer

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

public class TimerExample {
    private static int counter = 0;

    public static void main(String[] args) {
        // Set up the frame
        JFrame frame = new JFrame("Timer Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setLayout(new FlowLayout());

        // Create a label to show the timer value
        JLabel label = new JLabel("Counter: " + counter);
        frame.add(label);

        // Create a timer that updates the label every 1 second
        Timer timer = new Timer(1000, e -> {
            counter++; // Increment the counter
            label.setText("Counter: " + counter); // Update the label text
        });

        // Start the timer
        timer.start();

        // Display the frame
        frame.setVisible(true);
    }
}

🎨 Explanation

  • Timer(1000, e -> {...}): A timer that fires every 1000 milliseconds (1 second) and updates the counter.
  • e -> {...}: The ActionListener lambda expression is executed every time the timer fires.
  • label.setText(): Updates the label to show the current counter value.

πŸ‘©β€πŸŽ¨ Output:

You will see a window with a label showing the counter, which increments by 1 every second.


πŸ“š Step 2: Timer with Custom Animation

Now let’s use the timer to create a simple animation where an object moves across the screen.


πŸ“ Example: Moving Ball Animation

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

public class AnimationExample {
    private static int x = 0; // Starting position of the ball
    private static final int BALL_DIAMETER = 30;

    public static void main(String[] args) {
        // Set up the frame
        JFrame frame = new JFrame("Ball Animation");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setLocationRelativeTo(null); // Center the frame
        frame.setVisible(true);

        // Create a panel to draw the ball
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.RED);
                g.fillOval(x, 100, BALL_DIAMETER, BALL_DIAMETER); // Draw the ball
            }
        };

        frame.add(panel);

        // Create a timer to animate the ball
        Timer timer = new Timer(10, e -> {
            x += 1; // Move the ball to the right
            if (x > frame.getWidth()) {
                x = -BALL_DIAMETER; // Reset position when it moves off the screen
            }
            panel.repaint(); // Redraw the panel to update the ball's position
        });

        timer.start();
    }
}

🎨 Explanation

  • x += 1;: Moves the ball 1 pixel to the right on each timer tick.
  • panel.repaint();: Refreshes the panel to update the ball's position.
  • g.fillOval(x, 100, BALL_DIAMETER, BALL_DIAMETER);: Draws the ball at position (x, 100) on the screen.

πŸ‘©β€πŸŽ¨ Output:

The ball will continuously move across the screen, and once it moves off the right side, it will restart from the left.


πŸ“š Step 3: Timer with Indeterminate Progress

You can also use a timer to update a JProgressBar in an indeterminate manner.


πŸ“ Example: Indeterminate Progress with Timer

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

public class ProgressWithTimer {
    public static void main(String[] args) {
        // Set up the frame
        JFrame frame = new JFrame("Progress with Timer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 150);
        frame.setLayout(new BorderLayout());

        // Create an indeterminate progress bar
        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true); // Set to indeterminate mode
        frame.add(progressBar, BorderLayout.CENTER);

        // Create a timer to simulate a time-consuming task
        Timer timer = new Timer(5000, e -> {
            progressBar.setIndeterminate(false); // Stop the indeterminate animation
            JOptionPane.showMessageDialog(frame, "Task Complete!"); // Show message
        });

        timer.setRepeats(false); // Timer should run only once
        timer.start();

        // Display the frame
        frame.setVisible(true);
    }
}

🎨 Explanation

  • progressBar.setIndeterminate(true): Sets the progress bar to indeterminate mode.
  • timer.setRepeats(false): Ensures the timer only runs once after 5 seconds.
  • JOptionPane.showMessageDialog(): Displays a message when the task is complete.

πŸ‘©β€πŸŽ¨ Output:

The progress bar will show an indeterminate loading animation for 5 seconds. After the timer finishes, a message will pop up indicating the task is complete.


πŸ“š Step 4: Using Timers for Periodic Updates

Timers are also useful for periodically updating UI components, such as refreshing a status label or updating a clock.


πŸ“ Example: Digital Clock with Timer

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DigitalClock {
    public static void main(String[] args) {
        // Set up the frame
        JFrame frame = new JFrame("Digital Clock");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setLayout(new FlowLayout());

        // Create a label to display the time
        JLabel timeLabel = new JLabel();
        timeLabel.setFont(new Font("Serif", Font.BOLD, 40));
        frame.add(timeLabel);

        // Create a timer to update the time every second
        Timer timer = new Timer(1000, e -> {
            String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
            timeLabel.setText(time); // Update the label with the current time
        });

        timer.start();

        // Display the frame
        frame.setVisible(true);
    }
}

🎨 Explanation

  • SimpleDateFormat("HH:mm:ss").format(new Date()): Formats the current time into hours, minutes, and seconds.
  • Timer(1000, e -> {...}): The timer updates the time every second and updates the label.

πŸ‘©β€πŸŽ¨ Output:

The window will display a digital clock that updates every second to show the current time.