Search code examples
javaappletheight

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


I stumbled upon a bit of a problem while creating a simple Applet with a moving ball/circle/oval. I'm trying to set its' position to getHeight() / 2 but it doesn't seem to work: the ball ends up at the top of the Applet instead of the center. Where's the problem hiding?

Code

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());
    }

}

Solution

  • That is because until your Applet starts the getHeight() will return 0 . you need to assign y_pos in 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;
                }
            }
        }
    

    This will set right y_pos.