这部分代码来自我制作的动画类。它应该能够在一个单独的线程上运行动画,以免干扰我的程序的其他部分。该类扩展了Applet并实现了Runnable。
public void paint(Graphics g)
{
super.paint(g);
Graphics2D screen2D = (Graphics2D) g;
screen2D.drawImage(sprites[currentIndex].getImage(), x, y, null);
}
/**
* Will go through sprites and display the images
*/
public void run()
{
int currentIndex = 0;
while (playing)
{
if (currentIndex > sprites.length - 1)
{
currentIndex = 0;
}
try
{
repaint();
animateThread.sleep(speed);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
currentIndex++;
}
}
/**
* Will update the x and y so the images are drawn in the same location as the entity
*/
public void update(int newX, int newY)
{
this.x = newX;
this.y = newY;
}
/**
* Starts a new thread to play the animation on
*/
public void start()
{
playing = true;
//animateThread = (new Thread(() -> run()));
animateThread = new Thread(this);
animateThread.start();
}
下面的类是JFrame所在的位置,是制作和启动动画类的实例的地方。我没有收到任何错误,但JFrame窗口中没有显示任何错误。
public class AnimationTester extends Canvas
{
public JFrame frame;
private boolean running = false;
private Animation animation;
public AnimationTester()
{
Dimension size = new Dimension(400, 350);
//setPreferredSize is in the canvas class
setPreferredSize(size);
frame = new JFrame();
}
public static void main(String[] args)
{
AnimationTester tester = new AnimationTester();
tester.frame.setResizable(false);
tester.frame.setTitle("Tester");
tester.frame.add(tester);
tester.frame.pack();
tester.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tester.frame.setLocationRelativeTo(null);
tester.frame.setVisible(true);
//Make the window not have to be clicked on to get input (Set is as the main focus when it begins)
tester.requestFocusInWindow();
//Start the program
tester.start();
}
public void start()
{
try
{
animation = new Animation(ImageIO.read(getClass().getResource("/SpriteSheet.jpg")), 16, 2, 200, 250, 250, 2.0);
animation.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}