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

家住魔仙堡 提交于 2019-12-19 12:23:49

问题


I have a 2d game which 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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/6260744/how-do-i-set-up-a-jframe-with-a-refresh-rate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!