アニメーションを作成する一連の画像を表示するクラスを作成しました。私は、アニメーションをプログラムの残りの部分とは別のスレッドで実行したいと思います。しかし、アニメーションクラスを開始しようとすると、エラーが発生します。新しいスレッドはJFrameと連携しません
これはアニメーションクラス(そこよりですが、ある関係ありません)の一部である:私はまた、新しいオブジェクト全体を作り、その後、Runnableをアニメーションクラスを作るのが試みられてきた
/**
* Starts a new thread to play the animation on
*/
public void start()
{
playing = true;
animateThread = (new Thread(() -> run()));
animateThread.start();
}
/**
* Will go through sprites and display the images
*/
public void run()
{
int index = 0;
while (playing)
{
if (index > sprites.length)
{
index = 0;
}
try
{
g.drawImage(sprites[index].getImage(), x, y, null);
animateThread.sleep(speed);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
index++;
}
}
スレッドですが、私は同じエラーを受け取りました。
これは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()
{
createGraphics();
animation.start();
}
public void createGraphics()
{
BufferStrategy bs = getBufferStrategy();
//Checks to see if the BufferStrategy has already been created, it only needs to be created once
if (bs == null)
{
//Always do triple buffering (put 3 in the param)
createBufferStrategy(3);
return;
}
//Links the bufferStrategy and graphics, creating a graphics context
g = bs.getDrawGraphics();
try
{
animation = new Animation(ImageIO.read(getClass().getResource("/SpriteSheet.jpg")), 16, 2, 200, 250, 250, 2.0);
animation.addGraphics(g);
}
catch (IOException e)
{
e.printStackTrace();
}
}
について
を動作させるとしています方法の詳細については
BufferStrategy
とBufferStrategy and BufferCapabilitiesを詳しく見てみましょう状態を更新して画面に表示します – MadProgrammerエラーは何ですか? Sidenote: "if(index> sprites.length)"にバグがあります。これにより、インデックスが "sprites [index]"のスプライトにアクセスする際に使用されるsprites.lengthと等しくなるため、 ArrayIndexOutOfBoundsException。 "if(index == sprites.length)"に変更する必要があります – mmaarouf