java - 在 java 中实现 Swing Timer 的困难

标签 java swing timer

在这个 java 游戏中,我有一个动画类,它从 spritesheet 中渲染帧。具体针对攻击,我采用了不同的渲染方法 (renderAttack),因为我希望它渲染动画的所有 16 帧,每帧之间间隔 30 毫秒。我正在研究如何延迟 drawImage 调用,并决定 Swing 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
        } 
    }
}

为了等待这 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                    
        } 
    }
}

关于java - 在 java 中实现 Swing Timer 的困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838611/

相关文章:

java - 您如何检测 Java 虚拟机内存不足的情况?

java - 多线程下的 JList 重绘方法

iphone - 如何在 iOS 上处理时间事件?

适合新手的 Java UI 开发

C++ 非阻塞异步定时器

iOS 应用程序秒表和计时器在后台停止计数

java - 如何从您的 Activity 的前一个实例中判断线程已经完成?

java - JAXB 能否将基类型用于未知类型的已知元素?

java - Firestore 中 map 内的 map

java - 在 Javas 抽象表模型中显示某些列