【问题标题】:Why is my balls'/circles'/ovals' Y position calculated wrong?为什么我的球/圆/椭圆的 Y 位置计算错误?
【发布时间】: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()的值了吗?

标签: java applet height


【解决方案1】:

这是因为在您的 Applet 启动之前 getHeight() 将返回 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。

【讨论】:

  • 感谢您的帮助。
  • 很高兴为您提供帮助.. 干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多