Swing动画暂停和恢复 [英] Swing animation pause and resume

查看:44
本文介绍了Swing动画暂停和恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的游戏添加暂停/恢复的可能性.不幸的是,我的解决方案只会暂停游戏,但不会恢复它(当我单击恢复"按钮时没有任何反应 - 图像仍然存在).我还尝试在 thread 上调用 wait/notify 方法,但它也不起作用 - 我在线程AWT-EventQueue-0"java.lang.IllegalMonitorStateException 中遇到了 Exception.暂停/恢复的最佳解决方案是什么?

I want to add possibility to pause/resume to my game. Unfortunately my solution only pauses the game, but does not resume it (when I click resume button nothing happens - the image is still). I also tried to call wait/notify methods on thread, but it also did not work - I got Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException. What is the best solution to make pause/resume?

游戏循环

public void run() {
    init();

    long startTime;
    long reTime;
    long waitTime;

    while (running) {
        startTime = System.nanoTime();
        int CarPosX = car.zwrocPolozenieX();
        int CarPosY = car.zwrocPolozenieY();
        update(b, CarPosX, CarPosY);
        render(b);
        //draw();
        repaint();


        if(b<4390) {
            b=b+szybkoscMapy;
        }

        reTime = System.nanoTime() - startTime;
        waitTime = targetTime - reTime/100000000;
        try {
            Thread.sleep(waitTime);
        }
        catch(Exception e) {

        }
    }
}

public void init() {
    if(thread == null) {
        thread = new Thread(this);
        thread.start();
    }
    b=0;
    running = true;
    image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    g = (Graphics2D) image.getGraphics();


    map = new Map(levelNumber);
    car = new Car(map);
    car.setxpos(338);
    car.setypos(150);

}

听众

    pause_button.addActionListener( new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            bp.running = false;
        }
    });

resume_button.addActionListener( new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            bp.running = true;
        }
    });

推荐答案

使用 javax.swing.Timer 调整动画速度.检查了调用计时器的 start()stop() 方法的典型控件这里.这个舰队模拟,它使用了这样一个Timer,如果有兴趣也可以.

Use javax.swing.Timer to pace the animation. Typical controls that invoke the timer's start() and stop() methods are examined here. This fleet simulation, which uses such a Timer, may also be if interest.

这篇关于Swing动画暂停和恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆