repaint() 不调用 paintComponent()

repaint() not calling paintComponent()

首先,请不要在其他具有相似名称和内容的情况下创建问题而将我烧死。我仔细查看了所有这些,但没有找到解决方案。

调用 repaint() 绝对不会调用 paintComponent(),不管我怎么尝试。这是所有与问题相关的代码:

 @Override
   public void mouseClicked(MouseEvent e) {//User clicks on play button, creates a new Level object. Level extends JPanel.
     if(isOnPlayButton(e.getPoint())){
       GameState.setState(GameState.INGAME);
       Level l = new Level(2);
       l.setVisible(true);
       Tetris.getWindow().setContentPane(l);
       Soundtrack.updateAudio();
       System.out.println("Level panel created and content pane set");
     }
   }

按照预期,"Level panel created and content pane set" 打印到控制台。

@SuppressWarnings("serial")
public class Level extends JPanel implements ActionListener{

  private final int levelNum;

  public Level(int levelNum){
    this.levelNum = levelNum;

    this.repaint();//Although this should work in the constructor, how about a Timer that repaints for confirmation?
    new Timer(2*1000, this).start();
  }

  @Override 
  public void paintComponent(Graphics g){
    super.paintComponent(g); 
    g.drawImage(Tetris.getTexture("LevelBackdrop.png"), 0, 0, null);
    System.out.println("paintComponent - level painted");
    g.setColor(new Color(255, 255, 0));
    g.drawString("2", 355, 55);
  }

  public int getLevelNum() {
    return levelNum;
  }

  public double getGravity(){
    return levelNum/4;
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    this.repaint();
    System.out.println("Timer repainting");
  }

}

"paintComponent - level painted" 从不打印。 "Timer repainting" 按预期每 2 秒打印一次。

调用重绘时 level 对象的实际大小是多少?如果它的高度和宽度为零,则不会调用 paintComponent 方法。因为你从来没有打电话给setPreferredSize(...),我想这可能是原因。

如果这不能解决您的问题,请覆盖 Level 中的 repaint() 方法并打开它以查看它的实际作用(需要 jdk 安装)。