开发者

How do I set up a JFrame with a refresh rate?

开发者 https://www.devze.com 2023-03-11 17:36 出处:网络
I have a 2d game whic开发者_如何学JAVAh the entire structure is completely coded except the graphics. I am just updating the single component of a JFrame which is a Graphic containing 50 images. Each

I have a 2d game whic开发者_如何学JAVAh the entire structure is completely coded except the graphics. I am just updating the single component of a JFrame which is a Graphic containing 50 images. Each frame the images are in a different location hence the need for a refresh rate.

To paint, I have overridden the paintComponent() method, so all I really need to do is repaint the component (which, again, is just a Graphic) every 40ms.

How do you set up a JFrame with 25FPS?


It's a bad idea to refresh a JFrame. It's one of the few heavy components in Swing. The best way is to

  • identify the Panel that contains your animation
  • create a class that extends JPanel . i.e. GamePane extends JPanel
  • override paintComponent (no s)

Your title is misleading, you did the right thing.

  • in your JFrame create a runner class

/** Thread running the animation. */
private class Runner extends Thread
{
    /** Wether or not thread should stop. */
    private boolean shouldStop = false;
    /** Pause or resume. */
    private boolean pause = false;

    /** Invoke to stop animation. */
    public void shouldStop() {
        this.shouldStop = true;
    }//met

    /** Invoke to pause. */
    public void pauseGame() { pause = true; }//met
    /** Invoke to resume. */
    public void resumeGame() { pause = false; }//met

    /** Main runner method : sleeps and invokes engine.play().
     * @see Engine#play */
    public void run()
    {
        while( !shouldStop )
        {
            try {
                Thread.sleep( 6 );
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }//catch
            if( !pause )
            {
                engine.play();
                                    gamePane.repaint();

            }//if
        }//while
    }//met

    /** Wether or not we are paused. */
    public boolean isPaused() {
        return pause;
    }//met
}//class Runner (inner)

Your animation will be much smoother. And use MVC and events to refresh other parts of UI.

Regards, Stéphane


This AnimationTest uses javax.swing.Timer. A period of 40 ms would give a rate of 25 Hz.

private final Timer timer = new Timer(40, this);

Addendum: The timer's ActionListener responds by invoking repaint(), which subsequently calls your overridden paintComponent() method

@Override
public void actionPerformed(ActionEvent e) {
    this.repaint();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消