Galera, estou estudando Java2D e estou tentando animar várias bolas de forma que elas fiquem batendo na lateral da janela e assim seguindo outra direção.
Consegui fazer isso para uma única bola. Inclusive consegui fazer ela mudar para uma cor aleatória quando bate na lateral... hehe..
Agora, o que me intrigou é: Como eu adiciono mais bolas?? =S
Eu construi o código pensando que ao fazer funcionar uma bola, bastaria criar outras e adicioná-las ao Frame... mas não deu certo minha idéia.
Segue o código das duas Classes:
1) Classe "Bola.java":
package bola;
import java.awt.*;
import javax.swing.JPanel;
public class Bola extends JPanel
{
private int x;
private int y;
private int diametro;
private int direcaox = 0;
private int direcaoy = 0;
private Color cor;
public Bola (int x, int y, int diametro, Color cor) {
this.x = x;
this.y = y;
this.diametro = diametro;
this.direcaox = 0;
this.direcaoy = 0;
this.cor = cor;
}
@Override
public int getX() { return x; }
@Override
public int getY() { return y; }
public int getDirecaoX() { return direcaox; }
public int getDirecaoY() { return direcaoy; }
public int getDiametro() { return diametro; }
public Color getCor() { return cor; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public void setDirecaoX(int direcaox) { this.direcaox = (direcaox); }
public void setDirecaoY(int direcaoy) { this.direcaoy = direcaoy; }
public void setDiametro(int diametro) { this.diametro = diametro; }
public void setCor(Color cor) { this.cor = cor; }
@Override
public void paintComponent(Graphics g)
{
g.setColor(getCor());
g.fillOval(getX(), getY(), getDiametro(), getDiametro());
}
public void move(int l, int x, int y) {
this.setX(x);
this.setY(y);
this.esperar(l);
}
public void esperar(int l) {
try
{
Thread.sleep(l);
}
catch (InterruptedException e) { }
}
}
2) Classe: "Janela.java"
package bola;
import java.awt.*;
import javax.swing.JFrame;
public class Janela{
public static void main(String[] args) {
JFrame frame = new JFrame();
Bola bola = new Bola(0,100,100,Color.black);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(bola);
frame.setSize(600,400);
frame.setVisible(true);
float a=0,b=0,c=0;
int x = bola.getX();
int y = bola.getY();
int l=10;
while(true){
bola.move(l, x, y);
if(bola.getDirecaoX() == 0){x++;}
if(bola.getDirecaoY() == 0){y++;}
if(bola.getDirecaoX() == 1){x--;}
if(bola.getDirecaoY() == 1){y--;}
if(x==((( (frame.getWidth()- bola.getDiametro()) - 10) /2 )-2 ) ){bola.setDirecaoX(1);bola.setCor(Color.getHSBColor(a, b, c));} //4
if(y==((( (frame.getHeight()- bola.getDiametro()) - 35) /2 )-2 ) ){bola.setDirecaoY(1);bola.setCor(Color.getHSBColor(a, b, c));}//28
if(x==0){bola.setDirecaoX(0);bola.setCor(Color.getHSBColor(a, b, c));}
if(y==0){bola.setDirecaoY(0);bola.setCor(Color.getHSBColor(a, b, c));}
frame.repaint();
a = (float) (Math.random()*255);
b = (float) (Math.random()*255);
c = (float) (Math.random()*100);
}
}
}