repaint()没有调用paintComponent()

时间:2016-08-26 22:12:28

标签: java swing user-interface paintcomponent repaint

首先,请不要因为创建问题而将我烧死,而其他名称和内容相似的人则存在。我仔细查看了所有内容,但没有找到解决方案。

调用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");
     }
   }

按照预期,“创建的关卡面板和内容窗格设置”将打印到控制台。

@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”永远不会被打印出来。正如预期的那样,“定时器重新绘制”每2秒打印一次。

1 个答案:

答案 0 :(得分:4)

调用重绘时,level对象的实际大小是多少?如果它的高度和宽度为零,则不会调用paintComponent方法。由于您从未致电setPreferredSize(...),我认为这可能就是原因。

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