简体   繁体   中英

Swing animation pause and resume

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?

Game Loop

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

}

Listeners

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

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.

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