簡體   English   中英

在Java中實現Swing Timer的困難

[英]Difficulty with implementing a Swing Timer in java

在這個Java游戲中,我有一個動畫類,可從Spritesheet渲染幀。 專門針對攻擊,我制作了一個不同的渲染方法(renderAttack),因為我希望它渲染動畫的所有16幀,每幀之間的間隔為30毫秒。 我一直在研究如何延遲drawImage調用,並決定Swing計時器可能是最好的選擇。 但是,我要花上最困難的時間。這是我想要做的,沒有計時器:

public class Animation {

    public void renderAttack(Graphics g, int x, int y, int width, int height) {

        for(int index = 0; index < 16; index++)
        {
            g.drawImage(images[index], x, y, width, height, null);
            //wait 30ms
        } 
    }
}

為了等待那30毫秒,我嘗試在這里使用計時器。 到目前為止,我有這個:

public class Animation {

    public void renderAttack(Graphics g, int x, int y, int width, int height) {

        ActionListener taskPerformer = new ActionListener();
        Timer timer = new Timer(30, taskPerformer);
        timer.start();
    }
}

但是,這將流向何處,它接收的ActionEvent是什么? 以及如何傳遞索引變量?

public void actionPerformed(ActionEvent e) {

    g.drawImage(images[index], x, y, width, height, null);
}

希望這有任何意義...我現在將逐步解決。

Swing是一個單線程環境。 您需要在單獨的線程中創建動畫。 我建議這樣的事情:

public class Animation {
    Image[] images = null;

    public Animation() {
        // Define your images here and add to array;        
    }

    class AttackTask extends SwingWorker<Void, Void> {

        Graphics g = null;
        int x,y,width,height;

        AttackTask(Graphics g, int x, int y, int width, int height) {
            this.g = g;
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }

        @Override
        protected Void doInBackground() throws Exception {

            for(int frame = 0; frame < 16; frame++)
            {
                g.drawImage(images[frame], x, y, width, height, null);
                Thread.sleep(30);
            }

            return null;
        }

        @Override
        protected void done() {
            // Do something when thread is completed                    
        } 
    }
}

暫無
暫無

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

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