如何消除更改标签中显示的图像之间的闪烁?

How do I remove the flicker between changing the image that is displayed in a label?

我有四张图片,我在它们之间循环以创建一个简单的动画。每个图像都是一个重复动画的帧,我有一个计时器将图像更改为下一帧以使其动画化。每次我更改图像时,都会出现闪烁,其中 window 在显示下一张图像之间全是白色。如何消除这种闪烁?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Reveal extends JFrame
{
    private JPanel panel = new JPanel(); //a panel to house the label
    private JLabel label = new JLabel(); //a label to house the image
    private String[] image = {"Jack in the Box 1.png","Jack in the Box 2.png","Jack in the Box 3.png","Jack in the Box 4.png","Jack in the Box 5.png","Jack in the Box 6.png","Jack in the Box 7.png"}; //an array to hold the frames of the animation
    private ImageIcon[] icon = new ImageIcon[7]; //an array of icons to be the images

    private Timer timer;
    private Timer timer2;
    int x = 0;
    int y = 4;
    int counter = 0;
/**
 * Constructor for objects of class Reveal
 */
public Reveal()
{
    for (int h = 0; h < 7; h++){
      icon[h] = new ImageIcon(image[h]);
      icon[h].getImage().flush();
      label.setIcon(icon[h]);
    }

    //Display a title.
    setTitle("Raffel");

    //Specify an action for the close button.
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Sets the size of the window
    setSize(800,850);
    panel = new JPanel();
    label = new JLabel();
    panel.add(label);

    add(panel);

    setVisible(true);
}

public void display(String name, int number){
    timer = new Timer(150, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            if (counter > 48){
            timer.stop();
            timer2.start(); //starts the second half of the animation
          }else{
            label.setIcon( icon[x] );
            if (x != 3){
                x++;
            }else{
                x = 0;
            }
            counter++;
          } //ends if-else
        } //ends action method
    }); //ends timer

    timer2 = new Timer(150, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
          if (y > 6) {
            timer2.stop();
          }else{
            label.setIcon( icon[y] );
            y++;
          } //ends if-else
        } //ends action method
    }); //ends timer2

    timer.start();
    }
}
icon[x] = new ImageIcon(image[x]);
icon[x].getImage().flush();
label.setIcon( icon[x] );

我建议您不要一直从磁盘读取图像。

在 class 的开头将所有 ImageIcons 加载到数组中,然后循环遍历数组以获取下一个图标以更新标签。

编辑:

The animation has only 4 unique frames.

但是你有一个包含 7 个图标的数组。

icon[h].getImage().flush();

不需要冲洗。您只是在创建 ImageIcons。

label.setIcon(icon[h]);

为什么每次新建Icon都要设置label的icon?这意味着最后创建的图标将是第一个显示的图标。

我希望您应该在循环结束后将图标[0] 分配给标签。我猜这是闪烁的原因,因为最后一个图标在第一个之前短暂显示。因此,如果您默认为第一个,则不会有问题。

The animation has only 4 unique frames. The animations is 64 frames long playing each image as a frame 16 times

为此您不需要 2 个计时器。你需要两个变量。

  1. 一直递增到 64 然后停止动画
  2. 一个不断增加到 3 然后重置为 0