我正在尝试使用gif显示一些动画。我使用了Image和ImageIcon。我在这里所做的是,我正在使用一个线程绘制三幅相同的图像。
此代码中发生的是,图像第一次运行良好,并将动画显示为gif图像。但是,其他时候,它仅显示带有第二帧的静止图像。
public class Check extends JFrame {
private JLabel statusbar;
private JLabel timer;
public Check() {
initUI();
}
private void initUI() {
statusbar = new JLabel("");
timer = new JLabel("Time Starts Now");
add(statusbar, BorderLayout.SOUTH);
add(timer, BorderLayout.NORTH);
add(new CheckBoard(statusbar,timer));
setResizable(false);
pack();
setTitle("Minesweeper");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Check ex = new Check();
ex.setVisible(true);
});
}
}
CheckBoard.java
public class CheckBoard extends JPanel implements Runnable{
private static JLabel statusbar;
private static JLabel timer;
private int x,y;
public CheckBoard(JLabel statusbar, JLabel timer) {
setPreferredSize(new Dimension(500, 500));
this.statusbar = statusbar;
this.timer = timer;
Thread threadsss= new Thread(this);
x=50;
y=50;
threadsss.start();
}
@Override
public void paintComponent(Graphics g) {
try{
Image icon = new ImageIcon(getClass().getResource("/resources/anim.gif")).getImage();
g.drawImage(icon,x,y, this);
}
catch(Exception e){
e.printStackTrace();
}
}
public void run(){
for(int i=0;i<=3;i++){
try{
Thread.sleep(2000);
}catch(Exception e){
}
x+=50;
y+=50;
repaint();
}
}
}
我非常确定这是缓存问题。有人可以