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