简体   繁体   中英

Difficulty with implementing a Swing Timer in java

In this java game, I have an animation class that renders frames from a spritesheet. For the attack specifically, I made a different render method (renderAttack) because I want it to render all 16 frames of the animation, with 30 milliseconds in between each. I was looking into how to do delay the drawImage call, and decided a Swing Timer may be the best option. However, I am having the hardest time putting this in. Here is what I am trying to do, WITHOUT the timer:

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
        } 
    }
}

To wait those 30 ms, I tried using the timer here. And as of now I have this:

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();
    }
}

However, where would this go, and what is the ActionEvent that it takes in? And how can I pass in the index variable?

public void actionPerformed(ActionEvent e) {

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

Hopefully this made any sense...I'll fix it step by step for now.

Swing is a single threaded environment. You need to create your animation in a separate thread. I would suggest something like this:

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                    
        } 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM