Create bouncing ball animation with Swing and ScheduledThreadPoolExecutor - Java 2D Graphics

Java examples for 2D Graphics:Animation

Description

Create bouncing ball animation with Swing and ScheduledThreadPoolExecutor

Demo Code

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.swing.JApplet;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Main {
  public static final int WIDTH = 350;
  public static final int HEIGHT = 300;

  public static void main(String[] argv) {
    JFrame f = new JFrame();
    f.setSize(WIDTH, HEIGHT);/*from   w  w  w  . java 2 s.  co  m*/
    
    PaintSurface canvas;
    
    canvas = new PaintSurface();
    f.add(canvas, BorderLayout.CENTER);

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3);
    executor.scheduleAtFixedRate(new AnimationThread(f), 0L, 20L, TimeUnit.MILLISECONDS);
    
    f.setVisible(true);
  }
}

class AnimationThread implements Runnable {
  JFrame c;

  public AnimationThread(JFrame c) {
    this.c = c;
  }

  public void run() {
    c.repaint();
  }
}

class PaintSurface extends JComponent {
  public ArrayList<Ball> balls = new ArrayList<Ball>();

  public PaintSurface() {
    for (int i = 0; i < 10; i++)
      balls.add(new Ball(20));
  }

  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(Color.RED);
    for (Ball ball : balls) {
      ball.move();
      g2.fill(ball);
    }
  }
}

class Ball extends Ellipse2D.Float {
  private int x_speed, y_speed;
  private int d;
  private int width = Main.WIDTH;
  private int height = Main.HEIGHT;

  public Ball(int diameter) {
    super((int) (Math.random() * (Main.WIDTH - 20) + 1), (int) (Math.random() * (Main.HEIGHT - 20) + 1),
        diameter, diameter);
    this.d = diameter;
    this.x_speed = (int) (Math.random() * 5 + 1);
    this.y_speed = (int) (Math.random() * 5 + 1);
  }

  public void move() {
    if (super.x < 0 || super.x > width - d)
      x_speed = -x_speed;
    if (super.y < 0 || super.y > height - d)
      y_speed = -y_speed;
    super.x += x_speed;
    super.y += y_speed;
  }
}

Related Tutorials