Search code examples
javaswingpaintcomponent

The rectangle is not moving the way I want it to


I have written this java code, where I want the blue rectangle to move around like a bounding ball, all over the frame. But when I am trying to run the code, it seems to be stuck in one position and is moving in one line. Here is the following code.

import javax.swing.*;
import java.awt.*;

public class MoveBody extends JFrame {
    BallPanel ballpanel;
    JFrame frame;

    int X=15;
    int Y=15;


    boolean up=false;
    boolean down=true;
    boolean left=false;
    boolean right=true;




    public static void main(String[]args)
    {

        new MoveBody().go();
    }


    private void go()
    {

            frame = new JFrame("Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            ballpanel = new BallPanel();

            frame.getContentPane().add(BorderLayout.CENTER, ballpanel);
            frame.setVisible(true);
            frame.setResizable(false);
            frame.setSize(500,500);
            frame.setLocation(375, 55);
            moveIt();
    }



class BallPanel extends JPanel
{
    public void paintComponent(Graphics g)
    {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        g.setColor(Color.WHITE);
        g.fillRect(10, 10, this.getWidth()-10,this.getHeight()-10);
        g.setColor(Color.BLUE);
        g.fillRect(X,Y, 50, 50);
    }
}

public void moveIt()
{

    while(true)
    {
        if(this.Y>=450);
        {
            up=true;
            down=false;
        }

        if(this.X<=10)
        {
            right=true;
            left=false;
        }

        if(this.Y<=10)
        {
            down=true;
            up=false;
        }

        if(this.X>=450)
        {
            right=false;
            left=true;
        }

        if(left) X-=5;
        if(right) X+=5;
        if(up) Y-=5;
        if(down) Y+=5;

        try
        {
            Thread.sleep(50);
        }catch(Exception e){}

        frame.repaint();
    }


}




}

Solution

  • Here's the error:

    if(this.Y>=450);   <----
    {
        up=true;
        down=false;
    }
    

    remove the ; and it works as intended.

    (By having that trailing ; you end the if-statement and execute the { ... } block regardless of the condition. That's why the square bounced up and down so quickly.)