My first attempt at a basic java applet failed. i can't figure out why the rectangle is not moving

public class Basics extends Applet{

int x = 0;

int y = 0;

    public void init(){
        setSize(500,500);
    }

    public void start(){
        Thread a = new Thread();
        a.start();
    }

    public void run(){
        while(true){
            x = 100;
            y = 100;                
            repaint();
            try{
                Thread.sleep(18);
            }
            catch(InterruptedException e){}
        }

    public void paint(Graphics g){
        g.setColor(Color.red);
        g.fillRect(this.x,this.y,25,25);
    }

}

      

Do not increment x and y and then redraw so the square can move

+3


source to share


2 answers


You have to increment your x and y values, now you only assign values ​​to it. Change it like this:



public void run(){
        while(true){
            x += 100;
            y += 100;                
            repaint();
            try{
                Thread.sleep(18);
            }
            catch(InterruptedException e){}
        }

      

+6


source


In your startup method, you don't increment X and Y, you set them.

Try to do



x += 100;
y += 100;

      

I would use lower values, but I start at 1.

0


source







All Articles