简体   繁体   中英

Java Swing 'game loop' best practices

To make things clear, I'm looking for the best possible alternative to implement a 'game loop' in Java (using Swing).

Currently, I'm using the following setup with paintComponent() overridden in the JPanel class for drawing stuff like so:

public void run() {
    while (running) {
        panel.update();
        panel.repaint();
        try {
            sleep(SLEEP_TIME);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

This setup seems to work neatly, but moving shapes and images seems to stutter for a pixel or two at times. In other words, the movement isn't as smooth as I'd like it to be.

I'm wondering if there's a way to do the game loop more efficiently, ie to avoid stuttering in the movement?

An easy way to make the cycle rate fixed, is using ScheduledExecutorService .

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
    panel.update();
    panel.repaint();
}, 0, 16, TimeUnit.MILLISECONDS);

Another way is doing it by yourself by calculating the time to sleep based on the time used for the process.

public void run() {
    long time = System.currentTimeMillis();
    while (running) {
        panel.update();
        panel.repaint();
        long sleep = 16 - (System.currentTimeMillis() - time);
        time += 16;
        try {
            sleep(sleep);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

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