如何修复Java中的动画滞后? [英] How to fix animation lags in Java?

查看:110
本文介绍了如何修复Java中的动画滞后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的代码在 JComponent 的子类中使用Java动画我的游戏,但是此代码会导致动画中出现滞后和抖动,并且对象看起来像是分裂的在屏幕上快速重绘。我该如何解决这个问题?我应该在单独的线程上重绘每个项目吗?

I am trying to animate my game in Java using the code below in a subclass of JComponent, but this code causes lags and jitters in the animation, and objects appear to be "split" as they are redrawn rapidly on the screen. How can I resolve this issue? Should I redraw each item on a separate thread?

public GameScene(){
   setDoubleBuffered(true);
   run();
}

...
public void run() {
    Thread animation = new Thread(new Runnable() {
        public void run() {
            updateGraphics();
        }
    });

    animation.start();
}

public void updateGraphics() {
    while (true) {
        repaint();

        try {
            Thread.sleep(5);
        } catch (Exception ex) {

        }
    }
}


推荐答案

你很模糊地描述你的问题。

You describe your issue pretty vaguely.

原则上,Swing不是全部非常适合动画 - 速度不是主要问题 - 而是缺乏控制何时在屏幕上更新图形的可能性。

In principle, Swing isn't all that well suited for animation - speed isn't the principal problem - rather its the lack of a possibility to control when exactly the graphics are updated on screen.

Swing不同步用屏幕刷新渲染。虽然它确实是双缓冲区(默认情况下),但是在显示屏幕时刷新图形仍然会发生(并且确实如此),在组件框架N的上半部分显示(例如),而框架N + 1在下半部分(因为帧更新发生在屏幕刷新位于屏幕中间某处)。

Swing does not synchronize rendering with screen refresh. While it does double buffer (by default), it can (and does) still happen that the graphics are refreshed while the screen is displayed, displaying (for example) in the top half of the component frame N, while frame N+1 in the lower half (because the frame update happened while the screen refresh was somewhere in the middle of the screen).

我所知道的唯一解决方案是切换到全屏模式( http://docs.oracle.com/javase/tutorial/extra/fullscreen/ ),其中渲染可以是波束同步的。窗口显示没有解决方案(据我所知)。

The only solution I know of is switching to full screen mode (http://docs.oracle.com/javase/tutorial/extra/fullscreen/), where rendering may be beam synchronized. There is no solution for windowed display (to my knowledge).

这篇关于如何修复Java中的动画滞后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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