gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:57:09 24 4
gpt4 key购买 nike

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

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[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

关于java - 如何消除更改标签中显示的图像之间的闪烁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52154861/

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