我在编码方面相对较新,并试图制作一个显示简短3幅图像动画的GUI。为此,我在GUI上的JLabel中将图像显示为ImageIcon,并尝试让程序在按下按钮后在每个图像之间以300毫秒的定时延迟旋转3个图像。我的代码没有任何错误,但是当我运行它时,它不会将动画显示为动画。它只显示动画的最后一个图像。这几乎就像JLabel在运行整个actionperformed方法之前没有更新。
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AnimatedGui extends JFrame{
//The imageIcon and JLabel thing is how I am adding the images to the GUI
JButton button1;
private ImageIcon image1;
private ImageIcon image2;
private ImageIcon image3;
final JLabel label1 = new JLabel();
public static void main(String[] args) {
// TODO Auto-generated method stub
new AnimatedGui();
}
public AnimatedGui(){
//Declare Variables
button1 = new JButton();
image1 = new ImageIcon(getClass().getResource("Stick man Standing.jpg"));
image2 = new ImageIcon(getClass().getResource("Stick man first step.jpg"));
image3 = new ImageIcon(getClass().getResource("Stick man ending.jpg"));
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
JPanel panel = new JPanel();
label1.setIcon(image1);
//setting up gui
this.setSize(500,600);
int xPos = (dim.width)-(this.getWidth());
int yPos = 0;
this.setLocation(xPos,yPos);
this.setResizable(false);
this.setTitle("Trying to Animate");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
ListenForButton listenButton = new ListenForButton();
button1.addActionListener(listenButton);
button1.setText("Walk");
panel.add(label1);
panel.add(button1);
this.add(panel);
this.setVisible(true);
}
//Here I am trying to get it to wait 300 ms between showing each image
//but it only shows the final image in the animation
private class ListenForButton implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
int period = 300;
long lastTime = System.currentTimeMillis();
while(System.currentTimeMillis()-lastTime<300){
label1.setIcon(image2);
}
while(System.currentTimeMillis()-lastTime<600&&System.currentTimeMillis()-lastTime>300){
label1.setIcon(image3);
}
while(System.currentTimeMillis()-lastTime>600){
label1.setIcon(image1);
}
}
}
}
如果有人能帮助我,我会非常感激。
答案 0 :(得分:0)
您可以使用许多工具制作gif。只是搜索如何制作一个GIF。如果要在按钮单击时为其设置动画,则可以显示jpg以开始,然后在按钮单击时切换到gif。您可以使用任意数量的图像来制作您的GIF。顶部再次停止,您需要将其替换为要停止的图像的jpg。停止gif变得更加复杂,所以我建议用jpg替换它。