Space_Shift Space_Shift - 3 years ago 142
Java Question

Having problems on moving a rectangle figure using threads

I'm having some problems on an exercise from my Java class, i made two rectangles on the game and i need that those figures move from one side to another. I already have the movement class and made the instance of the thread of the movement but it doesn't seem to move.

This is the code i have atm:
Entity class

class Entity implements Drawable{
Point pos;
Rectangle body;
boolean rigid;

public Entity(){
pos = new Point(0,0);
body = new Rectangle(pos, new Dimension(0,0));

public Entity(Point p, Dimension d){
pos = new Point(p);
body = new Rectangle(pos, d);

public Entity(int x, int y, int width, int height){
pos = new Point(x,y);
body = new Rectangle(pos, new Dimension(width, height));

public BufferedImage getActualImage(){
Dimension d = body.getSize();
return new BufferedImage(d.width, d.height, BufferedImage.TYPE_3BYTE_BGR);

This class is the game environment and where i add the objects on the window.

class Field extends JPanel{
Player p1;
int i=0;
static ArrayList<Entity> objects = new ArrayList<Entity>();

private ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {

public Field(){

//Implementar patron de disen/o
p1 = setupPlayer();

//Player p2 = new Player();

Entity e1 = new Entity(0, 520, 600, 50);
Blocks block1 = new Blocks(260, 370, 100, 20);
Blocks block2 = new Blocks(190, 440, 100, 20);
Goal block3 = new Goal(300, 270, 50,50);
new Thread(new MovementBlock(block1)).start(); //movement thread//
PlayerBehaviour pb = new PlayerBehaviour(p1);
Timer tick = new Timer(20, actionListener);

The block class

class Blocks extends Entity{
public Blocks(int x, int y, int ancho, int largo){

And the thread for the movement

class MovementBlock implements Runnable{
Blocks block;
int velX = 2;
public MovementBlock(Blocks block){
this.block = block;

public void run(){
if(block.pos.x < 0 || block.pos.x > 500){
velX = -velX;
block.pos.x = block.pos.x + 1;

This is the code i have for the blocks and the movement, is there something i'm not considering for the movement?

Thanks for reading.

Answer Source

If the movement is a continuous action, then the run method needs to be a loop. The way you've written it, it will run once and only once. Add this to MovementBlock.

boolean running = true;
int frameDelay = 20; // ms

public void stop() { running = false; }

public void run() {
    while (running) {
        try {
            if (block.pos.x < 0 || block.pos.x > 500) {
                velX = -velX;
            block.pos.x += velX;
        } catch (InterruptedException e) {}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download