Mastering Java Swing
Looping Circle
Animations With SwingAnimations in Swing are typically achieved by repeatedly updating the position or properties of components and then redrawing them. The simplest way to create animations is by using the javax.swing.Timer class to schedule periodic updates.
import javax.swing.*;
import java.awt.*;
public class Main extends JPanel {
private int x = 0; // Initial X position of the ball
private final int y = 100; // Fixed Y position
private final int DIAMETER = 50; // Diameter of the ball
public Main() {
Timer timer = new Timer(10, e -> {
x += 2; // Move the ball to the right
if (x > getWidth()) { // Reset position when it moves off screen
x = -DIAMETER;
}
repaint(); // Redraw the panel
});
timer.start(); // Start the animation timer
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // Clears the panel for fresh drawing
g.setColor(Color.RED); // Set ball color
g.fillOval(x, y, DIAMETER, DIAMETER); // Draw the ball
}
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.add(new Main());
frame.setVisible(true);
}
}Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 27 more lessons in Mastering Java Swing.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.