0

i paint the square at x,y and then increment x and y in the run method before repainting but the square doesnt move

import java.applet.*;
import java.awt.*;
public class Basics extends Applet implements Runnable{
int x = 0;
int y = 0;

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

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

public void stop(){

}

public void destroy(){

}

public void run(){


    while(true){
        x++;
        y++;                
        repaint();
        try{
            Thread.sleep(18);
        }
        catch(InterruptedException e){}


    }
}

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

}

however, even if i dont increment x and y and just set a value for them in the run method the square paints at 0,0;

  • `new Thread(this);` but wait for the answers; there still might be something to say. – Joop Eggen Dec 05 '14 at 15:17
  • 1) Why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT using components in favor of Swing. – Andrew Thompson Dec 06 '14 at 23:47

2 Answers2

1

You have implemented the Runnable interface in your class, implying that you want it to be run in the thread. But you declare and start your thread without ever specifying what you want it to do.

Try passing your Runnable object (i.e. this) to the Thread constructor, so the thread will have something to do.

Thread a = new Thread(this);
khelwood
  • 55,782
  • 14
  • 81
  • 108
0

Specify the applet as the runnable to use when constructing the thread. Change the following line:

Thread a = new Thread();

to:

Thread a = new Thread( this );
paulscode
  • 1,049
  • 1
  • 12
  • 29