Java Graphics Updating Too Fast

2019-09-02 23:31发布

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.

1条回答
姐就是有狂的资本
2楼-- · 2019-09-03 00:20

"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

enter image description here

查看更多
登录 后发表回答