Keep distance between objects in Java [closed]

1

I have 3 balls within a JPanel that move at random speeds. Until then everything is fine. But I want the balls always to be at an equal distance, for example that the vertical distance between each one is 50 pixels.

package jFrameLluvia; 
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class Gota {
    private int x;
    private int y;
    private int radio;
    private int retraso;
    private Random r;
    private int velocidad;

    public Gota() {
        this.r = new Random();
        this.radio = 5;
        this.x = 100;
        this.y = r.nextInt(250 + 2 * radio) - radio;
        this.retraso = r.nextInt(20) + 1;
        this.velocidad = (radio + 1) / radio;
    }

    public void moverse(int ancho) {
        if (retraso == 0) {
            if (x < ancho)
                x += velocidad;
            else {
                x = 150 + radio;
                this.retraso = (5) + 1;
            }
        } else
            retraso--;
    }

    public void dibujar(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillOval(x - radio, y - radio, 2 * radio, 2 * radio);
    }
}
    
asked by Kelsy Nuñez M 09.03.2016 в 23:13
source

1 answer

3

You can create a constructor in your class Gota that receives the value of Y as an argument and use the other default values for the rest of the fields. Here is an example:

public class Gota {
    //los otros campos permanecen tal cual
    private Random r = new Random();

    public Gota() {
        //se aprovecha utilizar this(arg) para delegar trabajo a otro constructor
        this.(r.nextInt(250 + 2 * radio) - radio);
    }

    public Gota(int y) {
        this.radio = 5;
        this.x = 100;
        this.y = y;
        this.retraso = r.nextInt(20) + 1;
        this.velocidad = (radio + 1) / radio;
    }

    //resto de métodos en la clase
}

And then you can create the other instances of Gota based on an instance you already have:

Gota gota1 = new Gota();
Gota gota2 = new Gota(gota1.getY());
    
answered by 14.03.2016 в 21:00