本程序实现逐帧动画的连续播放效果
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Move extends JFrame {
Toolkit toolkit=super.getToolkit();
Dimension screenSize=toolkit.getScreenSize();
int width=(int)(screenSize.width);
int height=(int)(screenSize.height);
Point pressedPoint;
public Move(){
ImgPanel p1=new ImgPanel(10,"image2/mov2/");//第一个参数为帧数,最多300帧。第二个参数为图片存放路径。
setLayout(new GridLayout());
add(p1);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
pressedPoint = e.getPoint();
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
Point point=e.getPoint();
Point locPoint=getLocation();//
int x=locPoint.x+point.x-pressedPoint.x;
int y=locPoint.y+point.y-pressedPoint.y;
setLocation(x,y);
}
});
}
public static void main(String[] args) {
Move frame=new Move();
frame.setTitle("动画");
frame.setSize(frame.width,frame.height);//使用屏幕分辨率更改程序界面大小;
frame.setResizable(false);//禁止改变窗口大小;
frame.setLocationRelativeTo(null);//将程序界面置于屏幕中央;
frame.setUndecorated(true);//去除 程序的window边框GUI;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(new Color(0,0,0,0));
frame.setVisible(true);
}
}
class ImgPanel extends JPanel{
private Image[] mov1=new Image[300];
private int i=0;
private int N;//设置动画帧数;
private String s;
Toolkit toolkit=super.getToolkit();
Dimension screenSize=toolkit.getScreenSize();
int width=(int)(screenSize.width);
int height=(int)(screenSize.height);
public ImgPanel(int N,String s){
this.N=N;
this.s=s;
setOpaque(false);//让JPanel背景透明;
for(int j=0;j<=N;j++)
{
mov1[j]=Toolkit.getDefaultToolkit().createImage(s+j+".png");
}
Timer timer=new Timer(100,new TimerListener());
timer.start();
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
int h=mov1[i].getHeight(null);
int w=mov1[i].getWidth(null);
if(mov1[i]!=null){
g.drawImage(mov1[i],this.width/2-h/2,this.height/2-h/2,this);
}
if(i<N){
i++;
}
else{
i=0;
}
}
class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
repaint();
}
}
}