Search code examples
javaloopsmethodspaintframe-rate

Call paint method in the game fps tick in java


How do i call for my paint method to draw everything inside it withing my thick method that runs 60 times per second.

this is the fps calculation :

int FRAMES_PER_SECOND = 60;
    long maxWorkingTimePerFrame = 1000 / FRAMES_PER_SECOND;  //this is optional
    long lastStartTime = System.currentTimeMillis();

    while(true)
    {
        lastStartTime = System.currentTimeMillis();

            Tick();

        long processingTimeForCurrentFrame = System.currentTimeMillis() - lastStartTime;
        if(processingTimeForCurrentFrame  < maxWorkingTimePerFrame)
        {
            try
            {
                Thread.sleep(maxWorkingTimePerFrame - processingTimeForCurrentFrame);
            }
            catch(Exception e)
            {
                System.err.println("TSEngine :: run :: " + e);
            }
        }
    }

so how do i call :

public void paint( Graphics g ) {

}

in my Tick method?


Solution

  • To call the paint() method in your Tick method, you need to call the repaint() method. In your loop, just add repaint() when you want your component to call the paint method that you wrote.

    Read this article, as it explains a little bit how painting and repainting work. http://www.scs.ryerson.ca/~mes/courses/cps530/programs/threads/Repaint/index.html.

    Here is an article demonstrating how to call repaint. http://www.scs.ryerson.ca/~mes/courses/cps530/programs/threads/Repaint/RepaintApplet3.java