HOWTO · Java

在 Java 中创建动画

本教程演示如何用 Java 制作动画。

本页内容

Java Swing 库中的 JFrame 类可用于在 Java 中创建不同的图形和动画。直到 JDK 8 小程序用来创建动画,但后来被删除了,加入了 JAVA swing。

本教程将讨论和演示使用 Java 创建动画。

在 Java 中使用 JFrame 类创建动画

使用 JFrame,我们可以决定动画的颜色、形状和时间。让我们创建一个包含三部分但六种颜色的二维旋转饼图。

package delftstack;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;

public class Animation extends JFrame {
  private static int DELAY = 500; // The speed on which the animation will run

  Insets animate_insets;

  Color colors[] = {Color.PINK, Color.GREEN, Color.ORANGE, Color.BLACK, Color.WHITE, Color.MAGENTA};

  public void paint(Graphics demo) {
    super.paint(demo);
    if (animate_insets == null) {
      animate_insets = getInsets();
    }
    int a = animate_insets.left;
    int b = animate_insets.top;
    int animation_width = getWidth() - animate_insets.left - animate_insets.right;
    int animation_height = getHeight() - animate_insets.top - animate_insets.bottom;
    int animation_start = 0;
    int animation_steps = colors.length;
    int animation_stepSize = 720 / animation_steps;
    synchronized (colors) {
      for (int i = 0; i < animation_steps; i++) {
        demo.setColor(colors[i]);
        demo.fillArc(a, b, animation_width, animation_height, animation_start, animation_stepSize);
        animation_start += animation_stepSize;
      }
    }
  }

  public void go() {
    TimerTask animation_task = new TimerTask() {
      public void run() {
        Color animation_color = colors[0];
        synchronized (colors) {
          System.arraycopy(colors, 1, colors, 0, colors.length - 1);
          colors[colors.length - 1] = animation_color;
        }
        repaint();
      }
    };
    Timer animation_timer = new Timer();
    animation_timer.schedule(animation_task, 0, DELAY);
  }

  public static void main(String args[]) {
    Animation Demo_Animation = new Animation();
    Demo_Animation.setSize(400, 400);
    Demo_Animation.show();
    Demo_Animation.go();
  }
}

上面的代码将生成一个包含三个部分和六种不同颜色的旋转饼图。

输出:

Java 中的动画

我们可以使用 Java swing 库创建具有不同形状和颜色的动画。