在创建一个带有移动球/圆/椭圆的简单Applet时,我偶然发现了一些问题。我试图将其位置设置为getHeight() / 2
,但它似乎不起作用:球最终位于Applet的顶部而不是中心。隐藏的问题在哪里?
public class MovingBall extends Applet implements Runnable {
int x_pos = 10;
int y_pos = getHeight() / 2;
int radius = 20;
int diameter = radius * 2;
public void init() {
setBackground(Color.white);
}
public void start() {
Thread thread = new Thread(this);
thread.start();
}
public void stop() {
}
public void destroy() {
}
public void run() {
while (true) {
x_pos++;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (x_pos > getWidth()) {
x_pos = 10;
}
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.fillOval(x_pos, y_pos, diameter, diameter);
g.fillRect(0, 0, getWidth(), 10);
g.fillRect(0, 0, 10, getHeight());
g.fillRect(0, getHeight() - 10, getWidth() - 10, 10);
g.fillRect(getWidth() - 10, 0, 10, getHeight());
}
}
答案 0 :(得分:2)
这是因为在您的Applet启动之前,getHeight()将返回0
。您需要在run()
public void run() {
y_pos = getHeight() / 2;
while (true) {
x_pos++;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (x_pos > getWidth()) {
x_pos = 10;
}
}
}
这将设置正确的y_pos。