Java 没有调用 paintComponents
Java paintComponents is not being called
我正在尝试在 JPanel
上画一些东西,但我似乎遇到了 paint
和 paintComponent
方法的问题。可能与双缓冲有关,但我不确定。 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();
}
*/
我认为 JFrame 不是 JComponent,因此永远不会调用 paintComponent 方法。
您应该将所有绘制方法放在 JPanel 中并将其包含在您的 JFrame 中。
您正在覆盖 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。
我正在尝试在 JPanel
上画一些东西,但我似乎遇到了 paint
和 paintComponent
方法的问题。可能与双缓冲有关,但我不确定。 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();
}
*/
我认为 JFrame 不是 JComponent,因此永远不会调用 paintComponent 方法。 您应该将所有绘制方法放在 JPanel 中并将其包含在您的 JFrame 中。
您正在覆盖 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。