在 Java 中创建动画
Java Swing 库中的 JFrame 类可用于在 Java 中创建不同的图形和动画。直到 JDK 8 小程序用来创建动画,但后来被删除了,加入了 JAVA swing。
本教程将讨论和演示使用 Java 创建动画。
在 Java 中使用 JFrame 类创建动画
使用 JFrame,我们可以决定动画的颜色、形状和时间。让我们创建一个包含三部分但六种颜色的二维旋转饼图。
package delftstack;
import java.awt.Graphics;
import java.awt.Color;
import java.util.Timer;
import java.awt.Insets;
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 swing 库创建具有不同形状和颜色的动画。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。