Search code examples
javaimagepaintgame-loop

java image appears and disappears when using game loop


game loop:

private int FPS = 25;
private int targetTime = 1000 / FPS;

public void run(){

    init();

    long start;
    long elapsed;
    long wait;

    while (running){

        start = System.nanoTime();
        init();
        repaint();
        elapsed = System.nanoTime()  - start;

        wait = targetTime - elapsed / 1000000;

        try {

            Thread.sleep(wait);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

the paint method:

/**draws the game graphics*/
public void paint(Graphics g){
    super.paint(g);
    Graphics2D g2 = (Graphics2D)g;

    gameStateHandler.draw(g2);

}

the method the that the paint method refers too:

private static  Image image = resourceLoader.getImage("/background/menu_background.png");
/**draws the menu state*/
public static void draw(Graphics2D g){

    g.drawImage(image, 0, 0, null);
}

i call the image from this method which is in the same folder of the image

static resourceLoader rl = new resourceLoader();

public static Image getImage(String image){

    return Toolkit.getDefaultToolkit().getImage(rl.getClass().getResource(image));
}

i have a game loop that it will call repaint(); 60 times per second and in the paint method it refers to a method where this method draws an image. everything seems nice and smooth and when i run the program the image appears and disappears at a fast time and sometimes the image appears and nothing bad happens but after a random amount of time the thing happens i changed the fps from low to high and from high to low still the same im using jpanel in this project


Solution

  • Okay, so there's a recommendation here, which could well be the fix you need:

    Use paintComponent() instead of paint()

    // draws the game graphics
    
    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;    
        gameStateHandler.draw(g2);    
    }
    

    paintComponent is the recommended way to use JPanels to paint in Java - see also a more detailed explanation of custom painting in Swing. It could well be that your use of paint() is what's causing your visual inconsistencies.

    Failing that, I recommend looking at how you're loading your resource, but that should work, so I don't think it's the issue.