Buenas.
Puedo mover dos bolas que rebotan mediante hilos pero no a la velocidad que determina el retardo de cada hilo.
Como puedo hacer que cada bola vaya a la velocidad que determine el retardo del thread?
He aqui lo que tengo hecho:
Código:
import java.awt.Color;
import javax.swing.JFrame;
public class Muevepelota extends JFrame {
public static void main(String[] args) {
Muevepelota f = new Muevepelota();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new PanelPelota());
f.setSize(450, 500);
f.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class PanelPelota extends JPanel implements Runnable{
Thread[] animabola;
Pelota[] p;
public PanelPelota(){
animabola = new Thread[2]; //Creo dos hilos
animabola[0]= new Thread(this);
animabola[1]= new Thread(this);
p = new Pelota[2]; //Creo un array con dos bolas.
p[0]= new Pelota(60,60,1,2,2,Color.red); // 2 velocidad del hilo: 2
p[1]= new Pelota(20,20,1,1,100,Color.blue); // velcidad del hilo: 100
for (int i=0; i<animabola.length; ++i) //Comenzamos cada hilo.
animabola[i].start();
}
public void run(){
while (animabola[0].currentThread()== animabola[0]) {
try {
animabola[0].sleep(p[0].retardo()); // Espera 50ms
}catch (InterruptedException e) { }
repaint();
}
while (animabola[1].currentThread()== animabola[1]) {
try {
animabola[1].sleep(p[1].retardo()); // Espera 50ms
}catch (InterruptedException e) { }
repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
p[1].pintar(g);
p[0].pintar(g);
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
public class Pelota {
private int x, y;
private int dsx, dsy, t; //dsx y dsy son los desplazamientos, t el retardo de la bola
private int radio = 5; //radio de la bola
private Color c;
public Pelota(int x, int y, int dsx, int dsy, int t, Color c ){
this.x=x;
this.y=y;
this.dsx= dsx;
this.dsy=dsy;
this.t=t;
this.c = c;
}
public int retardo (){ //retardo de la bola
return t;
}
public void pintar (Graphics g){
x=x + dsx;
y=y + dsy;
// comprueba si choca contra los bordes
if ( x>= 450-radio || x<= radio)
dsx = -dsx;
if ( y >= 500- radio || y<=radio )
dsy = -dsy;
// pinta la pelota
g.setColor(c);
g.fillOval(x-radio, y-radio, radio*4, radio*4);
// return g;
}
}
El problema esta aqui: que me pinta las dos bolas con el mismo retardo
public void paintComponent(Graphics g) {
super.paintComponent(g);
p[1].pintar(g);
p[0].pintar(g);
}
Como modificariais el codigo para que p[0] vaya a la velocidad que marca el retardo del hilo animabola[0] y p[1] vaya a la velocidad que marca el retardo del hilo animabola[1] ???
Un saludo y gracias.