【发布时间】:2016-09-13 15:42:31
【问题描述】:
我在创建一个带有移动球/圆形/椭圆形的简单小程序时偶然发现了一个问题。我正在尝试将其位置设置为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());
}
}
【问题讨论】:
-
你测试
getHeight()的值了吗?