新线程无法使用JFrame

时间:2016-04-08 23:54:55

标签: java multithreading jframe

我创建了一个显示一系列图像的类来创建动画。我希望动画发生在一个单独的线程上,而不是程序的其余部分。但是,当我尝试启动动画类时,我收到错误。

这是一些动画类(还有更多但是无关紧要)

    /**
     * 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++;
        }
    }

我还试图制作动画类Runnable,然后使整个对象成为一个新的Thread但是我收到了同样的错误。

这是包含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();
        }
    }

1 个答案:

答案 0 :(得分:0)

这不是BufferStrategy的工作原理,而不是使用createGraphics,你应该调用它来更新状态并将其渲染到屏幕

所以,在你的Thread中,应该以某种方式更新状态并调用一些“render”方法,该方法将获得下一页,呈现状态并将该状态推送到屏幕。

仔细查看BufferStrategyBufferStrategy and BufferCapabilities,了解有关其如何工作的详细信息

example