我开始学习Java游戏开发,目前正在学习this精彩教程。
开发的游戏是基于Applet的。
经过一番研究,我发现Applet是使用UIManager进行重量级组件Swing。
所以,当我阅读repaint()文档时,说:
repaint():
Repaints this component.
If this component is a lightweight component, this method
causes a call to this component's <code>paint</code>
method as soon as possible. Otherwise, this method causes
a call to this component's <code>update</code> method as soon
as possible.
我理解repaint()调用update(),因为Applet是一个重量级的组件,而不是paint()。
BUT
在游戏教程中,作家/'老师'说:
“ ...同样总是调用paint(),在run()方法中使用repaint()语句。”
这确实似乎正在发生。但是为什么repaint()调用paint()?
遵循代码(为重要部分修剪)。
由于
public class StartingClass extends Applet implements Runnable, {
private Robot robot;
private Image image, character;
private URL base;
private Graphics second;
@Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
base = getDocumentBase();
character = getImage(base, "data/character.png");
}
@Override
public void start() {
robot = new Robot();
Thread thread = new Thread(this);
thread.start();
}
@Override
public void stop() {
}
@Override
public void destroy() {
}
@Override
public void run() {
while (true) {
robot.update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);
g.drawImage(image, 0, 0, this);
}
@Override
public void paint(Graphics g) {
g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);
}
}