Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...