Java图形更新太快 [英] Java Graphics Updating Too Fast

查看:119
本文介绍了Java图形更新太快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了这个问题,但是每个人似乎都对图形更新太慢有疑问。



要介绍我的情况:



我有一个JFrame,可以通过使用兼容的显示模式将其设置为全屏显示。
在JFrame中,我有几个JPanels和JButtons ...
在一个JPanels上,我正在绘制需要更新的移动对象。



<我正在像这样更新图形:验证并重新绘制JFrame,然后重新验证并重新绘制相应的JPanel。
图形更新太快。 (我需要提到的是,在JPanel上,我重写了paintComponent方法)。
我尝试在JFrame上使用BufferStrategy,但是这将阻止我显示JPanels和JButton(不知道为什么)。



这种机会问你们中的一些人,是否可以在涂色,验证,重涂,重新验证,无效等之间做出清楚的区分……所有教程几乎都没有涉及到表面。

解决方案


计时机制只是一个循环,使用System.timeCurrentMillis对其进行了5分钟的计数


那是行不通的。如果没有延迟,循环最终将阻止绘画直到循环完成。



我建议您考虑使用 javax .swing.Timer 进行动画制作。您可以在如何使用摆动计时器

Timer 的基本结构如下

  Timer(int delayInMillis,ActionListener侦听器)

其中 delayInMillis 滴答声 listener 之间提供的延迟时间,以毫秒为单位c> actionPerformed ,它每 delayInMillis 毫秒被调用一次。因此,最终您会执行以下操作:

  Timer timer = new Timer(40,new ActionListener(){
public void actionPerformed (ActionEvent e){
表示(球:球){
ball.move();
repaint();
}
}
} );






您可以看到完整的示例此处




I have searched the problem, but everyone seems to have problems with graphics updating too slow.

To present my situation:

I have a JFrame which I set to full screen, by using a compatible display mode. Within the JFrame I have a couple of JPanels and JButtons... On one of JPanels I am drawing moving objects that need to be updated.

I am updating the graphics like this : validate and repaint the JFrame, then revalidate and repaint the corresponding JPanel. The graphics are updating too fast. (I need to mention that on the JPanel I am overriding the paintComponent method). I have tried to use BufferStrategy on the JFrame, however this will prevent me from showing the JPanels and JButtons (have no idea why).

I also take this oppurtunity to ask some of you guys if you can give a clear distinction between paint, validate, repaint, revalidate, invalidate, etc... all the tutorials barely scratch the surface.

解决方案

"The timing mechanism is simply a loop that runs for 5 minutes using System.timeCurrentMillis to count that"

That's not going to work. The loop is ultimately blocking the painting to occur until the loop is complete, if there is no delay.

I suggest you look into using a javax.swing.Timer for the animation. You can see more at How to Use Swing Timers

The basic construct of Timer is as follows

Timer ( int delayInMillis, ActionListener listener )

where delayInMillis is the time in milliseconds to delay between "ticks" and the listener provides the actionPerformed which is called every delayInMillis milliseconds. So ultimately you do something like

Timer timer = new Timer (40, new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        for (Ball ball: balls) {
            ball.move();
            repaint();
        }
    }
});


You can see a complete example here

这篇关于Java图形更新太快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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