noobcoder
noobcoder

Reputation: 41

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, i.e. to avoid stuttering in the movement?

Upvotes: 1

Views: 1122

Answers (1)

Bubletan
Bubletan

Reputation: 3863

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

Upvotes: 1

Related Questions