首先,请不要因为我创建了一个问题而烧死我,而其他名字和内容相似的人已经存在了。我把它们都看了一遍,但没有找到答案。
调用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秒打印一次,正如预期的那样。
调用重绘时level
对象的实际大小是多少?如果高度和宽度为零,则不会调用paintComponent
方法。因为你从来没有打过setPreferredSize(...)
,我想这可能是原因。
如果这不能解决你的问题,覆盖Level
中的repaint()
方法,并打破它,看看它实际做什么(需要安装jdk)。