Java 为什么我的球是'/圆圈'/椭圆形';Y位置计算错误?
在创建一个带有移动球/圆/椭圆的简单小程序时,我偶然发现了一点问题。我试图将其“位置”设置为Java 为什么我的球是'/圆圈'/椭圆形';Y位置计算错误?,java,applet,height,Java,Applet,Height,在创建一个带有移动球/圆/椭圆的简单小程序时,我偶然发现了一点问题。我试图将其“位置”设置为getHeight()/2,但它似乎不起作用:球最终位于小程序的顶部而不是中心。问题出在哪里 代码 这是因为在小程序启动之前,getHeight()将返回0。您需要在run() 这将设置正确的y位置。您是否测试了getHeight()的值。?感谢您的帮助。很高兴这对您有所帮助。。干杯 public class MovingBall extends Applet implements Runnable {
getHeight()/2
,但它似乎不起作用:球最终位于小程序的顶部而不是中心。问题出在哪里
代码
这是因为在小程序启动之前,getHeight()将返回
0
。您需要在run()
这将设置正确的y位置。您是否测试了
getHeight()的值。
?感谢您的帮助。很高兴这对您有所帮助。。干杯
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());
}
}
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;
}
}
}