簡體   English   中英

新線程無法與JFrame一起使用

[英]New Thread not working with 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();
        }
    }

這不是BufferStrategy的真正工作方式,而不是使用createGraphics ,應該調用它來更新狀態並將其呈現到屏幕上

因此,在您的Thread ,它應該以某種方式更新狀態並調用某種“ render”方法,該方法將獲取下一頁,呈現狀態並將該狀態推送到屏幕。

仔細研究BufferStrategyBufferStrategy和BufferCapabilities,以獲取有關如何工作的更多詳細信息

舉個例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM