为什么我的球/圆/椭圆的 Y 位置计算错误?

Why is my balls'/circles'/ovals' Y position calculated wrong?

我在创建带有移动 ball/circle/oval 的简单 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());
    }

}

那是因为在您的 Applet 启动之前,getHeight() 将 return 0 。您需要在 run()

中分配 y_pos
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。