Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the ball not starting at the right coordinates?

Tags:

java

I'm doing something where the ball bounces around the board from given coordinates but it's not working. No matter what I do, the ball always start moving from the top left.

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

 
public class Board extends JPanel {
    
  // Board dimensions
    int width;
    int height;
    
  // Ball size
    int radius = 4;
    int diameter = radius * 2;
    
  // Ball initial position
    int X = radius + 239;
    int Y = radius + 100;
    
  // Direction
    int dx = 3;
    int dy = 3;
    
    public Board() {
        Thread thread = new Thread() {
            public void run() {
                while (true) {
                    repaint();
                    width = getWidth();
                    height = getHeight();
                    
                    X = X + dx ;
                    Y = Y + dy;
                    
                    if (X - radius < 0) {
                        dx = -dx; 
                        X = radius;
                    } else if (X + radius > width) {
                        dx = -dx;
                        X = width - radius;
                    }
 
                    if (Y - radius < 0) {
                        dy = -dy;
                        Y = radius;
                    } else if (Y + radius > height) {
                        dy = -dy;
                        Y = height - radius;
                    }
                    
                    try {
                        Thread.sleep(10);
                    } catch(InterruptedException ex) {}
                }
            }
        };
        thread.start();
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLUE);
        g.fillOval((int)(X - radius), (int)(Y - radius), (int)diameter, (int)diameter);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Bouncing Ball");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 300);
        frame.setContentPane(new Board());
        frame.setVisible(true);
        frame.setResizable(false);
    }
}

Before adding the thread.start(); the ball is at the right position but as soon as I do, the ball goes back on the top left.

Help would be greatly appreciated!

like image 327
GunTish Avatar asked Dec 05 '25 18:12

GunTish


1 Answers

The issue is that your thread is started before the Board's JPanel is added to the JFrame and its layout determined, and so the width and height of the panel are zero.

The right thing to do is to wait until the frame and its panels are all set up before starting the thread.

One quick-and-dirty solution is to add a line like if (width == 0 || height == 0) continue; right after you get the width and height. This relies on the fact that panels are initially created with a width and height of zero, and so it now won't do any calculations with your ball until you have a non-zero size for your board.

A better solution would be to do something like this at the end of your main function:

 EventQueue.invokeLater(new Runnable() {
        public void run() {
            board.thread.start();
        }
 });

This assumes that you are now storing your board in a variable called board and that your Board class stores its Thread in a field called thread. This will wait until Swing is done with other tasks on its event queue (and thus has finished setting up your frame and panel) before starting your thread.

like image 185
Andrew Merrill Avatar answered Dec 08 '25 07:12

Andrew Merrill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!