gpt4 book ai didi

java - 褪色 sample

转载 作者:行者123 更新时间:2023-11-29 05:59:28 26 4
gpt4 key购买 nike

我需要一个用 Java 编写的颜色褪色示例。我的要求是我有两个矩形。一个填充红色,另一个填充白色。当我点击任何按钮时,我希望红色开始褪色并移动绿色。一旦到达绿色位置,另一个矩形就会自动从黄蓝色开始。有人可以帮我吗?如果有任何用 Javaswing 或 SWT 编写的示例将会很好。谢谢。

最佳答案

结帐 Trident动画库。它允许您轻松地在您的类中插入属性。还要检查 these来自 Kirill Grouchnikov(Trident 的作者)的原始教程。

编辑:没有三叉戟的动画示例

以下示例基于 Filthy Rich Clients 中的 AnimatedGraphics 示例:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class AnimatedGraphics extends JComponent implements ActionListener {

Color startColor = Color.RED; // where we start
Color endColor = Color.GREEN; // where we end
Color currentColor = startColor;
int animationDuration = 2000; // each animation will take 2 seconds
long animStartTime; // start time for each animation

public AnimatedGraphics() {
Timer timer = new Timer(30, this);
// initial delay while window gets set up
timer.setInitialDelay(1000);
animStartTime = 1000 + System.nanoTime() / 1000000;
timer.start();
}

public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(currentColor);
g.fillOval(0, 0, getWidth(), getHeight());
}

public void actionPerformed(ActionEvent ae) {
// calculate elapsed fraction of animation
long currentTime = System.nanoTime() / 1000000;
long totalTime = currentTime - animStartTime;
if (totalTime > animationDuration) {
animStartTime = currentTime;
}
float fraction = (float)totalTime / animationDuration;
fraction = Math.min(1.0f, fraction);
// interpolate between start and end colors with current fraction
int red = (int)(fraction * endColor.getRed() +
(1 - fraction) * startColor.getRed());
int green = (int)(fraction * endColor.getGreen() +
(1 - fraction) * startColor.getGreen());
int blue = (int)(fraction * endColor.getBlue() +
(1 - fraction) * startColor.getBlue());
// set our new color appropriately
currentColor = new Color(red, green, blue);
// force a repaint to display our oval with its new color
repaint();
}

private static void createAndShowGUI() {
JFrame f = new JFrame("Animated Graphics");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(200, 200);
f.add(new AnimatedGraphics());
f.setVisible(true);
}

public static void main(String args[]) {
Runnable doCreateAndShowGUI = new Runnable() {
public void run() {
createAndShowGUI();
}
};
SwingUtilities.invokeLater(doCreateAndShowGUI);
}
}

关于java - 褪色 sample ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10706409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com