在 Java 中建立動畫

Sheeraz Gul 2024年2月15日
在 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 庫建立具有不同形狀和顏色的動畫。

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook