Java GUI 没有图形的淡入淡出动画

标签 java swing user-interface

我正在使用 Java GUI 制作游戏,并且正在尝试制作一些淡入淡出的动画。我知道使用 Java 图形要容易得多,但为此,我使用 JLabels 和 Swing,所以我无法真正做到这一点。我想要做的淡入淡出动画是我改变 JLabel 的背景颜色,以逐渐的方式从一种颜色变为下一种颜色,所以我尝试做的方法是创建一个颜色数组并有一个TimerTask将JLabel的背景一一设置为每种颜色。

TimerTask task = new TimerTask() {
    @Override
    public void run() {
        setBackground(c);
    }
};
tasks[i] = task;

这是我的计时器任务。颜色 c 是我放在这里作为示例的颜色,部分介于原始颜色和最终颜色之间。例如,如果我尝试从黑色淡入白色,则理想情况下,程序首先将颜色设置为深灰色,然后是中灰色,然后是浅灰色,最后是最终的白色。我测试了这些TimerTasks,它们似乎没有任何问题,所以我尝试使用Timer将它们一一执行,但似乎并不是每次都执行。

Timer timer = new Timer();
for (int i = 0; i < f; i++) {
    timer.schedule(tasks[i], delay);
}

通常最终发生的情况是颜色部分褪色,并且 JLabel 最终停留在原始颜色和最终颜色之间的某种颜色上,就好像没有完成所有计划的任务一样。我做错了什么,尝试使用 JLabels 制作动画是否明智?提前致谢!

<小时/>

编辑:很抱歉我之前的描述不太清楚。如果我提供原始代码的某些部分,也许会更容易,并且我会尝试解释我试图让它一点一点做什么。

/** Create array of colors **/
Color[] animationColors = new Color[f];      // f is the number of frames
// find difference between old and new values of r, g, b
int diffR = newColor.getRed() - oldColor.getRed();
int diffG = newColor.getGreen() - oldColor.getGreen();
int diffB = newColor.getBlue() - oldColor.getBlue();
// fill array with colors
for (int i = 0; i < f; i++) {
    int newR = (int)(diffR * (i + 1) / f) + oldColor.getRed();
    int newG = (int)(diffG * (i + 1) / f) + oldColor.getGreen();
    int newB = (int)(diffB * (i + 1) / f) + oldColor.getBlue();
    Color c = new Color(newR, newG, newB);
    animationColors[i] = c;
}

/** Set new background after each delay **/
int delay = (int)(t / f);         // t is the time that the animation will last in total
Timer timer = new Timer();
TimerTask task = new TimerTask() {
    @Override
    public void run() {
        animationCount++;
        if (animationCount == animationColors.length) {
            animationCount = 0;
            timer.cancel();
        } else {
            setBackground(animationColors[animationCount]);
        }
    }
};
timer.schedule(task, delay, delay);

首先,我尝试通过创建一个颜色数组来制作淡入淡出动画,JLabel 将在每个短时间间隔后将其设置为该颜色数组。我指定了动画将发生的多个帧,在第 1 帧,JLabel 的颜色将设置为位置 1 处的animationColors,第 2 帧的颜色将设置为位置 2 处的animationColors,依此类推。每一帧是从第一种颜色到最终颜色的逐渐淡入淡出,从黑色到白色的淡入淡出将从深灰色开始,然后是中灰色,浅灰色,最后是白色。

这里的问题是,瓷砖的颜色通常不会完全褪色。有时,它褪色的颜色最终会成为原始颜色,而不是我设置的最终颜色。问题可能出在我编写计时器的方式上,或者在 GUI 应用程序中使用计时器通常是一个坏主意?到目前为止,我阅读了对此问题的答复,但我不太明白其中的一些内容,因此如果您能对它们进行更多解释,我们也将不胜感激。

最佳答案

许多 Swing 组件不能很好地处理半透明度,尤其是当它发生变化时。

这是一个将标签绘制为 BufferedImage 的示例,然后可以将其用作另一个标签的图标。使用这种方法会失去标准标签的许多功能,但可能就足够了。

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.*;

public class FadingLabel {

    private JComponent ui = null;
    private BufferedImage fadeImage;
    private BufferedImage clearImage;
    private JLabel opaqueLabel;
    private JLabel fadeLabel;

    FadingLabel() {
        try {
            initUI();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }

    public final void initUI() throws MalformedURLException {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));
        URL url = new URL("/image/F0JHK.png");
        initialiseImages(url, "Fade me!");
        fadeLabel = new JLabel(new ImageIcon(fadeImage));
        ui.add(fadeLabel);

        ActionListener fadeListener = new ActionListener() {

            float transparency;
            float difference = .1f;

            @Override
            public void actionPerformed(ActionEvent e) {
                transparency += difference;
                if (transparency>=1f) {
                    difference = -.01f;
                    transparency = 1f;
                }
                if (transparency<=0f) {
                    difference = .01f;
                    transparency = 0f;
                }
                fadeImage(transparency);
                fadeLabel.repaint();
            }
        };
        Timer timer = new Timer(30, fadeListener);
        timer.start();
    }

    private void fadeImage(float transparency) {
        Dimension d = opaqueLabel.getSize();
        fadeImage.setData(clearImage.getData());
        Graphics2D g = fadeImage.createGraphics();
        Composite composite = AlphaComposite.getInstance(AlphaComposite.SRC, transparency);
        g.setComposite(composite);
        opaqueLabel.paint(g);
    }

    private void initialiseImages(URL iconURL, String text) {
        ImageIcon ii = new ImageIcon(iconURL);
        opaqueLabel = new JLabel(text, ii, SwingConstants.LEADING);
        opaqueLabel.setForeground(Color.BLUE);
        opaqueLabel.setSize(opaqueLabel.getPreferredSize());
        Dimension d = opaqueLabel.getSize();
        clearImage = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
        fadeImage = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
        Graphics g = fadeImage.getGraphics();
        opaqueLabel.paint(g);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            FadingLabel o = new FadingLabel();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

关于Java GUI 没有图形的淡入淡出动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030273/

相关文章:

iphone - 应用程序本身的应用程序名称

c++ - Qt 中的自动调整大小标签

java - 整理计算器界面

java - 需要帮助在 Amazon Web Service 上运行(托管)jar 文件

java - 空指针无处不在,因为数据突然变得稀疏

java - 如何使用 dataSnapshot.hasChildren() 检查 recyclerview 是否为空

Java - 这个简单的程序有什么问题?

java - 在 ActionListener 中调用对象不起作用,但在对象类 main 中起作用

android - 创建类似于 Google Fit 的圆环图

java - 如何额外配置自动创建的 Spring Boot bean?