user6120934
user6120934

Reputation:

Java paintComponents is not being called

I am trying to draw some things on the JPanel but it seems I have encountered an issue with the paint and paintComponent methods. Might have something to do with double buffering but I am not sure. public void paintComponent(Graphics g) method is not being called for some reason, any idea why?

here's my code:

   @Override
public void paintComponents(Graphics g) {
    super.paintComponents(g); //To change body of generated methods, choose Tools | Templates.
    System.out.println("paintComponents!");

    snakeHead.DrawSphere(g);

    if(foodShoulBeRedrawn){
        foodShoulBeRedrawn = false;
        spawnFood();
    }

    if(shouldSpawnBodyPart){
        shouldSpawnBodyPart = false;
        snake.get(snake.size() - 1).DrawSphere(g);

    }

    //spawnSnake();
    paintCalled = true;

    repaint();
}

/*
@Override
public void paint(Graphics g) {
    super.paint(g);

    snakeHead.DrawSphere(g);

    if(foodShoulBeRedrawn){
        foodShoulBeRedrawn = false;
        spawnFood();
    }

    if(shouldSpawnBodyPart){
        shouldSpawnBodyPart = false;
        snake.get(snake.size() - 1).DrawSphere(g);

    }

    //spawnSnake();
    paintCalled = true;

    repaint();
}
*/

Upvotes: 0

Views: 132

Answers (2)

Catalina Island
Catalina Island

Reputation: 7136

You're overriding Container#paintComponents(), which was inherited by your JFrame. Instead of extending JFrame, you need to extend JPanel so you can override its paintComponent() and getPreferredSize(). Then you can add() the panel to a JFrame, like they show here and here.

Upvotes: 3

zThulj
zThulj

Reputation: 149

I think JFrame is not a JComponent so paintComponent method is never going to be called. You should put all your paint methods in a JPanel and include it in your JFrame.

Upvotes: 0

Related Questions