Java paintComponents未被调用

时间:2016-06-13 12:09:21

标签: java swing paint paintcomponent

我想在JPanel上绘制一些内容,但似乎我遇到了paintpaintComponent方法的问题。可能与双缓冲有关,但我不确定。 public void paintComponent(Graphics g)方法由于某种原因没有被调用,任何想法为什么?

这是我的代码:

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

2 个答案:

答案 0 :(得分:3)

您将覆盖JFrame继承的Container#paintComponents()。您需要扩展JPanel,而不是扩展JFrame,以便覆盖其paintComponent()getPreferredSize()。然后,您可以add()将小组设为JFrame,就像他们显示herehere一样。

答案 1 :(得分:0)

我认为JFrame不是JComponent,因此永远不会调用paintComponent方法。 您应该将所有绘制方法放在JPanel中并将其包含在JFrame中。